<script lang="ts">
    import { format, fromUnixTime, getUnixTime, parse } from "date-fns";

    import {
        Input,
        InputGroup,
        InputGroupAddon,
        InputGroupText,
    } from "sveltestrap";
    import { SearchDateFormatStr } from "../api/util";

    interface IDateTimeParts {
        date: string;
        time: string;
    }

    const fromDateTimeParts = ({ date, time }: IDateTimeParts): Date =>
        parse(`${date} ${time}`, SearchDateFormatStr, new Date());

    const toDateTimeParts = (dt: Date = new Date()): IDateTimeParts => ({
        date: format(dt, "yyyy-MM-dd"),
        time: format(dt, "HH:mm:ss"),
    });

    const isDate = (v: string) =>
        (v.match(/[\d]{4}-\d{2}-\d{2}/) || []).length > 0;

    export let label: string = "label";
    export let defaultValue: Date = new Date();
    export let value: Date = defaultValue;

    $: dateTimeParts = toDateTimeParts(value);

    const update = ({ target: { value: v } }) => {
        const { date, time } = dateTimeParts;

        let dateTimePartsInput = isDate(v)
            ? { date: v, time }
            : { date, time: v };

        value = fromDateTimeParts(dateTimePartsInput);
        // dateTimeParts = toDateTimeParts(value);
    };
</script>

<InputGroup class="flex flex-row">
    <InputGroupAddon addonType="prepend">
        <InputGroupText>{label}</InputGroupText>
    </InputGroupAddon>
    <Input
        bsSize="sm"
        type="date"
        value={dateTimeParts.date}
        on:change={update}
    />
    <Input
        bsSize="sm"
        type="time"
        value={dateTimeParts.time}
        on:change={update}
    />
</InputGroup>
