<script lang="ts">
  import { onMount } from "svelte";
  import { endOfMonth, endOfWeek, endOfYear, formatFormTime, lastMonth, monthName, nextMonth, startOfMonth, startOfWeek, startOfYear } from "../utils/time";
  import EveryMinute from "./EveryMinute.svelte";

  interface DateOption {
    id: string
    label: string
    value: Date
  }

  export let value: string;
  export let disabled: boolean;

  let selected: string = "custom";
  let options: DateOption[] = [];
  let now: Date = new Date();

  onMount(() => {
    if (value === "") {
      selected = "none";
      return;
    }

    for (const option of options) {
      if (formatFormTime(option.value) === value) {
        selected = option.id;
      }
    }
  });

  $: {
    if (options.length === 0) {
      let current = startOfMonth(now);
      const nextWeek = new Date(now.getTime() + (86400000 * 7));
      const lastWeek = new Date(now.getTime() - (86400000 * 7));

      options.push({
        id: "none",
        label: "No deadline",
        value: new Date(Number.NaN),
      });

      options.push({
        id: "this_week",
        label: "End of this Week",
        value: endOfWeek(now),
      });
      options.push({
        id: "next_week",
        label: "End of next Week",
        value: endOfWeek(nextWeek),
      });
      options.push({
        id: "last_week",
        label: "End of last Week",
        value: endOfWeek(lastWeek),
      });

      options.push({
        id: "this_month",
        label: "End of this month",
        value: endOfMonth(current),
      });
      options.push({
        id: "next_month",
        label: "End of next month",
        value: endOfMonth(nextMonth(current)),
      });
      options.push({
        id: "last_month",
        label: "End of last month",
        value: endOfMonth(lastMonth(current)),
      });

      options.push({
        id: "this_year",
        label: "This Year",
        value: endOfYear(now),
      });
      options.push({
        id: "next_year",
        label: "Next Year",
        value: endOfYear(new Date(Date.now() + (365.25 * 86400000))),
      });
      options.push({
        id: "last_year",
        label: "Last Year",
        value: endOfYear(new Date(Date.now() - (365.25 * 86400000))),
      });

      options.push({
        id: "custom",
        label: "Specific Date",
        value: null,
      });
    }
  }

  $: {
    if (selected !== "custom") {
      const option = options.find(o => o.id === selected);
      if (option != null) {
        value = formatFormTime(option.value);
      }
    }
  }
</script>

<EveryMinute bind:now={now} />
<select name="endTime" disabled={disabled} bind:value={selected}>
  {#each options as option (option.id)}
    <option value={option.id}>{option.label}</option>
  {/each}
</select>
{#if selected === "custom"}
  <input disabled={disabled} name="value" type="datetime-local" bind:value={value} />
{/if}