<script lang="ts">
  import { onMount } from "svelte";
  import { startOfMonth, startOfWeek, startOfYear, formatFormTime, lastMonth, nextMonth } 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: "Project's creation date",
        value: new Date(Number.NaN),
      });

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

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

      options.push({
        id: "this_year",
        label: "Beginning of this year",
        value: startOfYear(now),
      });
      options.push({
        id: "next_year",
        label: "Beginning of next year",
        value: startOfYear(new Date(Date.now() + (365.25 * 86400000))),
      });
      options.push({
        id: "last_year",
        label: "Beginning of last year",
        value: startOfYear(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}