<script lang="ts">
  import { ImmutableStore, Store, UIEventSource } from "../../Logic/UIEventSource"
  import type { SpecialVisualizationState } from "../SpecialVisualization"
  import type { Feature } from "geojson"
  import Loading from "../Base/Loading.svelte"
  import Qr from "../../Utils/Qr"
  import { GeoOperations } from "../../Logic/GeoOperations"
  import { Utils } from "../../Utils"
  const smallSize = 100
  const bigSize = 200
  let size = new UIEventSource(smallSize)
  export let state: SpecialVisualizationState
  export let tags: UIEventSource<Record<string, string>>
  export let feature: Feature
  export let extraUrlParams: Record<string, string> = {}
  export let sideText: string = undefined
  export let sideTextClass: string = undefined

  const includeLayout = window.location.pathname.split("/").at(-1).startsWith("theme")
  let id: Store<string> = tags.mapD((tags) => tags.id)
  extraUrlParams["z"] ??= 15
  if (includeLayout) {
    extraUrlParams["layout"] ??= state.theme.id
  }
  if (feature) {
    const [lon, lat] = GeoOperations.centerpointCoordinates(feature)
    extraUrlParams["lon"] ??= "" + lon
    extraUrlParams["lat"] ??= "" + lat
  } else if (state?.mapProperties?.location?.data) {
    const l: { lon: number; lat: number } = state?.mapProperties?.location?.data
    if (l.lon !== 0 && l.lat !== 0) {
      extraUrlParams["lon"] ??= "" + l.lon
      extraUrlParams["lat"] ??= "" + l.lat
    }
  }

  const params = []
  for (const key in extraUrlParams) {
    console.log(key, "-->", extraUrlParams[key])
    params.push(key + "=" + encodeURIComponent(extraUrlParams[key]))
  }
  let url = id
    .map((id) => {
      if (id) {
        return "#" + id
      } else {
        return ""
      }
    })
    .map(
      (id) =>
        `${window.location.protocol}//${window.location.host}${
          window.location.pathname
        }?${params.join("&")}${id}`
    )

  function toggleSize() {
    if (size.data !== bigSize) {
      size.setData(bigSize)
    } else {
      size.setData(smallSize)
    }
  }

  let sideTextSub = (tags ?? new ImmutableStore({})).map((tgs) =>
    Utils.SubstituteKeys(sideText, tgs)
  )
</script>

{#if $id?.startsWith("node/-")}
  <!-- Not yet uploaded, doesn't have a fixed ID -->
  <Loading />
{:else}
  <div class="my-4 flex flex-col">
    <div class="flex w-full items-center">
      <img
        class="shrink-0"
        on:click={() => toggleSize()}
        src={new Qr($url).toImageElement($size)}
        style={`width: ${$size}px; height: ${$size}px`}
      />
      {#if sideText}
        <div class={sideTextClass}>{$sideTextSub}</div>
      {/if}
    </div>
    <a href={$url} target="_blank" class="subtle text-xs break-all">{$url}</a>
  </div>
{/if}
