import { Host, h } from "@stencil/core";
import dayjs from "dayjs";
import { Datepicker } from "vanillajs-datepicker";
import datePickerNlLocale from "vanillajs-datepicker/js/i18n/locales/nl.js";
import { getStore } from "../../store";
import { watchStoreLocale } from "../../utils/locale-state";
export class DatePicker {
    constructor() {
        /**
         * Time options used to populate the select element
         */
        this.timeOptions = [];
        this.datePicker = null;
        this.datePickerUnsubscribe = null;
        this.updateDateRangeFromSelect = (event) => {
            const selectElement = event.target;
            const selectedStart = dayjs(selectElement.value.split(",")[0]);
            const selectedEnd = dayjs(selectElement.value.split(",")[1]);
            const currentStart = dayjs(this.store.state.datePicker.start);
            this.store.state.datePicker = Object.assign(Object.assign({}, this.store.state.datePicker), {
                // Only overwrite the date, keep the time
                start: currentStart
                    .hour(selectedStart.hour())
                    .minute(selectedStart.minute())
                    .second(selectedStart.second())
                    .millisecond(selectedStart.millisecond())
                    .toISOString(),
                // Only overwrite the date, keep the time
                end: currentStart
                    .hour(selectedEnd.hour())
                    .minute(selectedEnd.minute())
                    .second(selectedEnd.second())
                    .millisecond(selectedEnd.millisecond())
                    .toISOString()
            });
        };
        this.decrementHour = () => {
            const currentStart = dayjs(this.store.state.datePicker.start);
            const currentEnd = dayjs(this.store.state.datePicker.end);
            this.store.state.datePicker = Object.assign(Object.assign({}, this.store.state.datePicker), { start: currentStart.subtract(1, "hour").toISOString(), end: currentEnd.subtract(1, "hour").toISOString() });
        };
        this.incrementHour = () => {
            const currentStart = dayjs(this.store.state.datePicker.start);
            const currentEnd = dayjs(this.store.state.datePicker.end);
            this.store.state.datePicker = Object.assign(Object.assign({}, this.store.state.datePicker), { start: currentStart.add(1, "hour").toISOString(), end: currentEnd.add(1, "hour").toISOString() });
        };
        this.incrementDay = () => {
            const currentStart = dayjs(this.store.state.datePicker.start);
            const currentEnd = dayjs(this.store.state.datePicker.end);
            this.store.state.datePicker = Object.assign(Object.assign({}, this.store.state.datePicker), { start: currentStart.add(1, "day").toISOString(), end: currentEnd.add(1, "day").toISOString() });
        };
        this.decrementDay = () => {
            const currentStart = dayjs(this.store.state.datePicker.start);
            const currentEnd = dayjs(this.store.state.datePicker.end);
            this.store.state.datePicker = Object.assign(Object.assign({}, this.store.state.datePicker), { start: currentStart.subtract(1, "day").toISOString(), end: currentEnd.subtract(1, "day").toISOString() });
        };
        /**
         * Use to initialize select dropdown options
         * @returns
         */
        this.getTimeOptions = () => {
            const timeFrameData = [];
            for (let i = 0; i < 24; i++) {
                const startLabel = i < 10 ? `0${i}` : i;
                const endLabel = i + 1 < 10 ? `0${i + 1}` : i + 1;
                timeFrameData.push({
                    value: [
                        dayjs(this.store.state.datePicker.start).hour(i).toISOString(),
                        dayjs(this.store.state.datePicker.end)
                            .hour(i + 1)
                            .toISOString(),
                    ],
                    label: `${startLabel}:00 - ${endLabel}:00`,
                });
            }
            return timeFrameData;
        };
    }
    resolveDatePickerLanguage() {
        var _a;
        const locale = (_a = this.store) === null || _a === void 0 ? void 0 : _a.state.locale;
        if (locale !== undefined && locale in Datepicker.locales) {
            return locale;
        }
        return "en";
    }
    async componentWillLoad() {
        Object.assign(Datepicker.locales, datePickerNlLocale);
        this.store = await getStore(this.idKey);
        watchStoreLocale(this, this.store, () => {
            var _a;
            (_a = this.datePicker) === null || _a === void 0 ? void 0 : _a.setOptions({ language: this.resolveDatePickerLanguage() });
        }, { skipForceUpdate: true });
        this.timeOptions = this.getTimeOptions();
    }
    componentDidLoad() {
        // Select the date picker element
        const datePickerElement = this.element.shadowRoot.querySelector("#date-picker");
        // Initialize the date picker
        const datePicker = new Datepicker(datePickerElement, {
            language: this.resolveDatePickerLanguage(),
        });
        this.datePicker = datePicker;
        // Set today as the selected date
        datePicker.setDate(dayjs(this.store.state.datePicker.start).valueOf());
        // Subscribe to date picker element changes
        datePickerElement.addEventListener("changeDate", (_event) => {
            const selectedDate = dayjs(new Date(datePicker.getDate().toString())); // Only way to get the selected date consistently
            const currentStart = dayjs(this.store.state.datePicker.start);
            const currentEnd = dayjs(this.store.state.datePicker.end);
            this.store.state.datePicker = Object.assign(Object.assign({}, this.store.state.datePicker), {
                // Only overwrite the date, keep the time
                start: selectedDate
                    .hour(currentStart.hour())
                    .minute(currentStart.minute())
                    .second(currentStart.second())
                    .millisecond(currentStart.millisecond())
                    .toISOString(),
                // Only overwrite the date, keep the time
                end: selectedDate
                    .hour(currentEnd.hour())
                    .minute(currentEnd.minute())
                    .second(currentEnd.second())
                    .millisecond(currentEnd.millisecond())
                    .toISOString()
            });
        });
        // Subscribe to store changes
        this.datePickerUnsubscribe = this.store.onChange("datePicker", ({ start }) => {
            datePicker.setDate(dayjs(start).valueOf());
            // Update the time options (needed for the timestamp values)
            this.timeOptions = this.getTimeOptions();
        });
    }
    disconnectedCallback() {
        var _a;
        (_a = this.datePickerUnsubscribe) === null || _a === void 0 ? void 0 : _a.call(this);
        this.datePickerUnsubscribe = null;
    }
    render() {
        return (h(Host, { key: 'c5eb536488a213da984ae1ad6e30ffd508c009fd' }, h("input", { key: '968840482d76e581fd28aaa1b9f7cbcb33b9450e', type: "text", id: "date-picker" }), h("select", { key: '88312412fc1eaabac3c9a5a6366d18f0278f34e1', onInput: this.updateDateRangeFromSelect }, this.timeOptions.map(({ value, label }) => (h("option", { value: value, selected: value[0] === this.store.state.datePicker.start &&
                value[1] === this.store.state.datePicker.end }, label)))), h("button", { key: 'ca1bfe9e12d9b21f8afe6ee324b63358449215e4', onClick: this.decrementHour }, "\u2039"), h("button", { key: 'e01d86a90e5997aeb8caa5491040c912b32ca318', onClick: this.incrementHour }, "\u203A"), h("button", { key: '798c6b3345ae1861771dc53bc6658828d9c8c35f', onClick: this.decrementDay }, "\u00AB"), h("button", { key: '6a569bdb6bfba39167e5faeb190d8c052f3f25be', onClick: this.incrementDay }, "\u00BB")));
    }
    static get is() { return "ls-date-picker"; }
    static get encapsulation() { return "shadow"; }
    static get originalStyleUrls() {
        return {
            "$": ["ls-date-picker.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["ls-date-picker.css"]
        };
    }
    static get properties() {
        return {
            "idKey": {
                "type": "string",
                "attribute": "id-key",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "The unique key that is used to identify store data."
                },
                "getter": false,
                "setter": false,
                "reflect": false
            }
        };
    }
    static get elementRef() { return "element"; }
}
//# sourceMappingURL=ls-date-picker.js.map
