<script lang="ts">
  import { Utils } from "../../Utils"
  import type { ChartConfiguration } from "chart.js"
  import ChartJs from "../Base/ChartJs.svelte"
  import { ChartJsUtils } from "../Base/ChartJsUtils"
  import { Lists } from "../../Utils/Lists"

  export let values: Store<string[]>
  let counts: Store<Map<string, number>> = values.map((values) => {
    if (values === undefined) {
      return undefined
    }

    values = Utils.noNull(values)
    const counts = new Map<string, number>()
    for (const value of values) {
      const c = counts.get(value) ?? 0
      counts.set(value, c + 1)
    }

    return counts
  })

  let max: Store<number> = counts.mapD((counts) => Math.max(...Array.from(counts.values())))
  let keys: Store<string> = counts.mapD((counts) => {
    const keys = Lists.dedup(counts.keys())
    keys.sort(/*inplace sort*/)
    return keys
  })
  let config: Store<ChartConfiguration> = keys.mapD(
    (keys) => ChartJsUtils.createHistogramConfig(keys, counts.data),
    [counts]
  )
</script>

{#if $config}
  <ChartJs config={$config} />
{/if}
