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

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

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

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

    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) => (v.match(/[\d]{4}-\d{2}-\d{2}/) || []).length > 0;

    let dateTimeParts = toDateTimeParts(defaultValue);

    const update = ({ target: { value } }) => {
        const { date, time } = dateTimeParts;
        let dateTimePartsInput = isDate(value)
            ? { date: value, time }
            : { date, time: value };

        const updatedDateTime = fromDateTimeParts(dateTimePartsInput);
        dateTimeParts = toDateTimeParts(updatedDateTime);
        console.log(dateTimeParts);
    };
</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>
