<script lang="ts">
  /**
   * Shows information about how much images are uploaded for the given feature
   *
   * Either pass in a store with tags or a featureId.
   */

  import type { SpecialVisualizationState } from "../SpecialVisualization"
  import { Store } from "../../Logic/UIEventSource"
  import type { NoteId, OsmTags, OsmId } from "../../Models/OsmFeature"
  import Translations from "../i18n/Translations"
  import Tr from "../Base/Tr.svelte"
  import Loading from "../Base/Loading.svelte"
  import UploadFailedMessage from "./UploadFailedMessage.svelte"

  export let state: SpecialVisualizationState
  export let tags: Store<OsmTags> = undefined
  export let featureId: OsmId | NoteId | "*" = tags?.data?.id ?? "*"
  if (featureId === undefined) {
    throw "No tags or featureID given"
  }
  export let showThankYou: boolean = true

  /*
  Number of images uploaded succesfully
   */
  function getCount(input: Store<string[]>): Store<number> {
    if (featureId == "*") {
      return input.map((inp) => inp.length)
    }
    return input.map((success) => success.filter((item) => item === featureId).length)
  }

  let successfull = getCount(state.imageUploadManager.successfull)
  /* Number of failed uploads */
  let failed = getCount(state.imageUploadManager.fails)

  let pending = getCount(state.imageUploadManager.queued)
  const t = Translations.t.image
  const debugging = state.featureSwitches.featureSwitchIsDebugging
  let dismissed = 0
  failed.addCallbackAndRun((failed) => {
    dismissed = Math.min(failed, dismissed)
  })
  let progress = state.imageUploadManager.progressCurrentImage
</script>

{#if $debugging}
  <div class="low-interaction">
    Pending {$pending} Done {$successfull} Err {$failed}
  </div>
{/if}

{#if $pending - $failed > 0}
  <div class="alert">
    <Loading>
      <div class="flex w-full flex-col">
        <div class="flex w-full justify-between gap-x-8">
          {#if $pending - $failed === 1}
            <Tr t={t.upload.one.uploading} />
          {:else if $pending - $failed > 1}
            <Tr t={t.upload.multiple.uploading.Subs({ count: $pending })} />
          {/if}
          {#if $progress !== undefined}
            {$progress}%
          {/if}
        </div>
        {#if $progress !== undefined}
          <div class="low-interaction h-1 w-full overflow-hidden rounded-full">
            <div class="h-1 bg-black" style={`width: calc(${$progress}%)`} />
          </div>
        {/if}
      </div>
    </Loading>
  </div>
{/if}

{#if $failed > dismissed}
  <UploadFailedMessage failed={$failed} on:click={() => (dismissed = $failed)} />
{/if}

{#if showThankYou}
  {#if $successfull === 1}
    <Tr cls="thanks" t={t.upload.one.done} />
  {:else if $successfull > 1}
    <Tr cls="thanks" t={t.upload.multiple.done.Subs({ count: $successfull })} />
  {/if}
{/if}
