import t from "../../i18n/index.js";
import { getRuntimeConfig } from "../../services/runtime.js";
import { snackbar } from "../../user-interface/common/eden-snackbar.js";
export async function selectBlockDates(block) {
    const { timeProgrammableBlocks } = getRuntimeConfig();
    if (!timeProgrammableBlocks) {
        return;
    }
    const selectedDates = block.element.dataset.dates;
    const copiedDates = window.sessionStorage.getItem("copiedDates");
    const { default: SelectDatesModal } = await import("../../user-interface/plugin/select-dates-modal.js");
    new SelectDatesModal(block.changeDates, copiedDates, selectedDates).init();
}
export function applyBlockDates(block, dates) {
    if (dates === "[]") {
        delete block.element.dataset.dates;
    }
    else {
        block.element.dataset.dates = dates;
    }
    snackbar(t("snackbars.applied-dates"), "success");
}
export function checkBlockDates(block) {
    cleanupBlockDatesCheck(block);
    if (!block.element.dataset.dates) {
        return;
    }
    const now = new Date();
    const dates = JSON.parse(block.element.dataset.dates);
    const active = dates.reduce((acc, [start, end]) => {
        const dateStart = new Date(start);
        const dateEnd = new Date(end);
        const isActive = dateStart <= now && now <= dateEnd;
        if ((acc === false && isActive) ||
            (acc !== false && dateStart <= new Date(acc))) {
            return end;
        }
        return acc;
    }, false);
    if (active) {
        block.element.dataset.datesActive = formatDate(active);
        return;
    }
    const scheduled = dates.reduce((acc, [start]) => {
        const dateStart = new Date(start);
        const isScheduled = now <= dateStart;
        if ((acc === false && isScheduled) ||
            (acc !== false && dateStart <= new Date(acc))) {
            return start;
        }
        return acc;
    }, false);
    if (scheduled) {
        block.element.dataset.datesScheduled = formatDate(scheduled);
    }
    else {
        block.element.dataset.datesScheduled = String(scheduled);
    }
}
export function cleanupBlockDatesCheck(block) {
    delete block.element.dataset.datesActive;
    delete block.element.dataset.datesScheduled;
}
function formatDate(date) {
    return new Date(date).toLocaleDateString("fr-FR", {
        year: "2-digit",
        month: "2-digit",
        day: "2-digit",
        hour: "2-digit",
        minute: "2-digit",
    });
}
