<script lang="ts">
    import { onMount } from 'svelte';
    import shortid  from 'shortid';

    import type { PlanDay, PlanWeek, PlanWeekItem } from '$lib/dashclient'
    import { dateUpdate, currentDate } from '$lib/stores/appStore'
    import { planApi } from '$lib/stores/apiStore'
    import type { PlanItem } from '$lib/stores/planStore'
    import PlanDndList from '$lib/components/plan/PlanDndList.svelte'
    import PlanTodoDndList from '$lib/components/plan/PlanTodoDndList.svelte'
    import InvertableIcon from '$lib/components/InvertableIcon.svelte';
    import InvertableButton from '$lib/components/InvertableIconButton.svelte';

    let updateTimeout: NodeJS.Timeout;
    let showWeek: boolean = false;
    
    interface DayItems {
        morning: Array<PlanItem>,
        midday: Array<PlanItem>,
        afternoon: Array<PlanItem>,
        evening: Array<PlanItem>
    }

    let planDay: PlanDay = {
        date: $currentDate,
        morning: [],
        midday: [],
        afternoon: [],
        evening: []
    };

    let planDayItems: DayItems = {
        morning: [],
        midday: [],
        afternoon: [],
        evening: []
    };

    let planWeek: PlanWeek = {
        date: $currentDate,
        items: []
    };

    let planWeekItems: Array<PlanItem> = [];

    function arrayToItems(arr: Array<string>): Array<PlanItem> {
        let items: Array<PlanItem> = [];
        
        if (arr) {
            arr.forEach((it) => {
                if (it.trim().length != 0) {
                    items.push({id: shortid.generate(), text:it});
                }
            })
        }
        
        return items;
    }

    function itemsToArray(items: Array<PlanItem>): Array<string> {
        let arr: Array<string> = [];

        items.forEach((it) => {
            if (it.text.trim().length != 0) {
                arr.push(it.text);
            }
        })
        
        return arr;
    }

    function arrayToWeekItems(arr: Array<PlanWeekItem>): Array<PlanItem> {
        let items: Array<PlanItem> = [];
        
        if (arr) {
            arr.forEach((it) => {
                if (it.item.trim().length != 0) {
                    items.push({id: shortid.generate(), text:it.item, todo: it.numTodo, done: it.numDone});
                }
            })
        }
        
        return items;
    }

    function weekItemsToArray(items: Array<PlanItem>): Array<PlanWeekItem> {
        let arr: Array<PlanWeekItem> = [];

        items.forEach((it) => {
            if (it.text.trim().length != 0) {
                arr.push({item: it.text, numTodo: it.todo, numDone: it.done});
            }
        })
        
        return arr;
    }
    
    function initPlanDay(plan: PlanDay) {
        planDay = plan;
        planDayItems = {
            morning: arrayToItems(planDay.morning),
            midday: arrayToItems(planDay.midday),
            afternoon: arrayToItems(planDay.afternoon),
            evening: arrayToItems(planDay.evening)
        }
    }

    function initPlanWeek(plan: PlanWeek) {
        planWeek = plan;
        planWeekItems = arrayToWeekItems(planWeek.items);
    }

    function preparePlanDayForWrite(items: DayItems): PlanDay {
        planDay.morning = itemsToArray(items.morning);
        planDay.midday = itemsToArray(items.midday);
        planDay.afternoon = itemsToArray(items.afternoon);
        planDay.evening = itemsToArray(items.evening);

        return planDay;
    }

    async function fetchPlan() {
        planApi.getPlanDayForDate({'date': $currentDate}).then(resp => (initPlanDay(resp)));
        planApi.getPlanWeekForDate({'date': $currentDate}).then(resp => (initPlanWeek(resp)));
    }

    onMount(() => {
        $dateUpdate = fetchPlan;
        fetchPlan();
    });
    
    function onInput() {
        clearTimeout(updateTimeout);
        
        updateTimeout = setTimeout(function() {
            planApi.savePlanForDay({planDay: preparePlanDayForWrite(planDayItems)});
        }, 1000);
    }
    
    function onInputWeek() {
        clearTimeout(updateTimeout);
        
        updateTimeout = setTimeout(function() {
            planApi.savePlanForWeek({planWeek: {date: planWeek.date, items: weekItemsToArray(planWeekItems)}});
        }, 1000);
    }

    function toggleWeek() {
        showWeek = !showWeek;
    }
</script>

<div class="m-4">
<div class="grid grid-cols-2 auto-cols-fr gap-1 justify-center content-center">
    <div class="flex flex-col min-w-[130px] grow basis-0 items-center">
        <div class="h-6 w-6 mt-1 mb-3">
            <InvertableIcon label="morgens" icon="/sun-regular.svg"/> 
        </div>
        <div class="w-full">
          <PlanDndList bind:items={planDayItems.morning} onInput={onInput}/>
        </div>
    </div>

    <div class="flex flex-col min-w-[130px] grow basis-0 items-center">
        <div class="h-6 w-6 mt-1 mb-3">
            <InvertableIcon label="mittags" icon="/sun-solid.svg"/> 
        </div>
        <div class="w-full">
          <PlanDndList bind:items={planDayItems.midday} onInput={onInput}/>
        </div>
    </div>

    <div class="flex flex-col min-w-[130px] grow basis-0 items-center">
      <div class="h-6 w-6 mt-1 mb-3">
        <div class="h-7 w-7">
            <InvertableIcon label="nachmittags" icon="/mountain-sun-solid.svg"/> 
        </div>
      </div>
        <div class="w-full">
          <PlanDndList bind:items={planDayItems.afternoon} onInput={onInput}/>
        </div>
    </div>

    <div class="flex flex-col min-w-[130px] grow basis-0 items-center">
      <div class="h-6 w-6 mt-1 mb-3">
        <div class="h-5 w-5">
            <InvertableIcon label="abends" icon="/moon-solid.svg"/> 
        </div>
      </div>
        <div class="w-full">
          <PlanDndList bind:items={planDayItems.evening} onInput={onInput}/>
        </div>
    </div>
  </div>

  <!-- <div>
    <div class="weekButton">
        <InvertableButton label="week" icon="/calendar-week-solid.svg" clickHandler={toggleWeek}/>
    </div>

    {#if showWeek}
    <div class="timeOfDay">
        <div class="timeIcon">
            <InvertableIcon label="week" icon="/calendar-week-solid.svg"/> 
        </div>
        <PlanTodoDndList bind:items={planWeekItems} onInput={onInputWeek}/>
    </div>
    {/if}
</div> -->
</div>