<script lang="ts">
  import { dateUpdate, currentDate } from '$lib/stores/appStore';
  import Choice from '$lib/components/ChoiceInput.svelte';
  import Boolean from '$lib/components/BooleanInput.svelte';

  import { onMount } from 'svelte';

  import { trackingApi } from '$lib/stores/apiStore'

  let updateTimeout: NodeJS.Timeout;

  let categories: trackingApi.TrackingCategories = {
    categories: []
  };

  let trackingEntry: trackingApi.TrackingEntry = {
    date: $currentDate,
    items: []
  };

  async function getTrackingCategories() {
    trackingApi.getTrackingCategories().then(resp => {
      console.log(resp);
      categories = resp;
    });
  }

  async function getTrackingEntry() {
    await trackingApi.getTrackingEntryForDate({"date": $currentDate}).then(resp => {
      trackingEntry = resp;
    });

    await getTrackingCategories();
  }

  function writeTrackingEntry() {
    clearTimeout(updateTimeout);
    console.log(trackingEntry);

    updateTimeout = setTimeout(function() {
      trackingApi.writeTrackingEntry({"trackingEntry": trackingEntry}).then(() => {
        // getTrackingEntry();
      });
    }, 1000);
  }

  function getOrAddItem(type): trackingApi.TrackingItem {
  let item = trackingEntry.items.find(item => item.type === type);
  if (!item) {
    item = { date: $currentDate, type: type, value: "false" };
    trackingEntry = { ...trackingEntry, items: [...trackingEntry.items, item] };
  }

  return trackingEntry.items.find(item => item.type === type);
}


  function handleSelection(type, newValue) {
   let item = trackingEntry.items.find(item => item.type === type);
    if (item) {
      item.value = newValue;
      trackingEntry = { ...trackingEntry }; // Trigger reactivity
    }
    writeTrackingEntry(); // Save the updated entry
  }

$: trackingEntry = { ...trackingEntry };

  onMount(async () => {
    await getTrackingEntry();
    $dateUpdate = getTrackingEntry;
    await getTrackingCategories();
  });
</script>

<div class="flex justify-center mt-8">
  <div class="flex flex-col w-11/12 items-center">
    <div>
      {#each categories.categories as category}
        <div class="flex flex-row w-full justify-between">
          <div class="w-32 min-w-32">
            {category.name}
          </div>
          <div class="w-full flex-grow">
          {#if category.type == "choice"}
            <Choice choices={category.items} selected={getOrAddItem(category.name).value} onInput={(newValue) => handleSelection(category.name, newValue)}/>
          {:else if category.type == "boolean"}
            <Boolean selected={getOrAddItem(category.name).value} onInput={(newValue) => handleSelection(category.name, newValue)}/>
          {/if}
          </div>
        </div>
      {/each}
    </div>
  </div>
</div>