import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useError, useMaybeBody, useMaybeResult, useTimezone } from "../../data/index.js";
import { ok } from "../../../../is.js";
import { dispatchEvent, isDispatchEvent } from "../../../../events/index.js";
import { DateTime } from "luxon";
import { DEFAULT_TIMEZONE } from "../../../../config/index.js";
export const path = "/durable-event/schedule";
export const MINUTE_MS = 60 * 1000;
export const DAY_MS = 24 * 60 * MINUTE_MS;
const FORM_CLASS = `
mt-1
block
w-full
md:max-w-sm
rounded-md
border-gray-300
shadow-sm
focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50
disabled:bg-slate-300 disabled:cursor-not-allowed
`.trim();
const FORM_GROUP_CLASS = `block py-2`;
function assertDispatchEvent(value) {
    ok(value);
    ok(isDispatchEvent(value));
}
export async function submit(request) {
    const data = request.body;
    assertDispatchEvent(data);
    ok(!Array.isArray(data.dispatch));
    let dispatching = {
        ...data.dispatch
    };
    if (data.data) {
        const parsed = JSON.parse(data.data);
        dispatching = {
            ...parsed,
            ...dispatching
        };
    }
    let schedule;
    if (data.schedule.immediate) {
        schedule = {
            immediate: true
        };
    }
    else {
        schedule = {};
        if (data.schedule.after) {
            schedule.timezone = data.schedule.timezone;
            schedule.after = fromWebDate(data.schedule.after, schedule.timezone);
        }
        if (data.schedule.before) {
            schedule.timezone = data.schedule.timezone;
            schedule.before = fromWebDate(data.schedule.before, schedule.timezone);
        }
        if (data.schedule.cron) {
            schedule.cron = data.schedule.cron;
        }
    }
    const event = await dispatchEvent({
        type: "dispatch",
        dispatch: dispatching,
        schedule,
        retain: !!data.retain
    });
    console.log({ event });
    return { success: true, event };
}
const LINK_CLASS = "text-blue-600 hover:bg-white underline hover:underline-offset-2";
export function ScheduleDurableEvent() {
    const body = useMaybeBody();
    const result = useMaybeResult();
    const error = useError();
    const timezone = useTimezone();
    console.error(error);
    return _jsx(DurableEventBody, { body: result?.success ? undefined : body });
    function DurableEventBody({ body }) {
        return (_jsxs("form", { name: "durable-event", action: `${path}#action-section`, method: "post", children: [_jsx("input", { type: "hidden", name: "type", value: "dispatch" }), _jsx("div", { className: "flex flex-col", children: _jsxs("label", { className: FORM_GROUP_CLASS, children: [_jsx("span", { className: "text-gray-700", children: "Event Type" }), _jsx("input", { className: FORM_CLASS, type: "text", name: "dispatch.type", placeholder: "Event Type", defaultValue: body?.type || "" })] }) }), _jsx("style", { dangerouslySetInnerHTML: { __html: `
                        
                form[name="durable-event"]:has(input[name="schedule.immediate"]:checked) .scheduled,
                form[name="durable-event"]:has(input[name="schedule.immediate"]:checked) .scheduled-flex {
                    display: none;
                }
                form[name="durable-event"]:has(input[name="schedule.immediate"]:not(:checked)) .scheduled {
                    display: block;
                }
                form[name="durable-event"]:has(input[name="schedule.immediate"]:not(:checked)) .scheduled-flex {
                    display: flex;
                }
                
                `.trim() } }), _jsxs("label", { htmlFor: "schedule.immediate", className: "my-4 flex flex-row align-start", children: [_jsx("input", { name: "schedule.immediate", id: "schedule.immediate", type: "checkbox", className: "form-checkbox rounded m-1", defaultChecked: body?.schedule?.immediate ?? true }), _jsx("span", { className: "flex flex-col ml-4", children: "Dispatch Immediately" })] }), _jsxs("label", { className: `${FORM_GROUP_CLASS} scheduled`, children: [_jsx("span", { className: "text-gray-700", children: "Timezone" }), _jsx("select", { name: "schedule.timezone", className: FORM_CLASS, defaultValue: body?.schedule?.timezone || timezone, children: _jsx("option", { value: "Pacific/Auckland", children: "Pacific/Auckland" }) })] }), _jsxs("label", { className: `${FORM_GROUP_CLASS} scheduled`, children: [_jsx("span", { className: "text-gray-700", children: "Dispatch After" }), _jsx("input", { className: FORM_CLASS, type: "datetime-local", name: "schedule.after", placeholder: "Dispatch After", defaultValue: body?.schedule?.after || "" })] }), _jsxs("label", { className: `${FORM_GROUP_CLASS} scheduled`, children: [_jsx("span", { className: "text-gray-700", children: "Dispatch Before" }), _jsx("input", { className: FORM_CLASS, type: "datetime-local", name: "schedule.before", placeholder: "Dispatch Before", defaultValue: body?.schedule?.before || "" })] }), _jsxs("label", { htmlFor: "retain", className: "scheduled-flex my-4 flex-row align-start", children: [_jsx("input", { name: "retain", id: "retain", type: "checkbox", className: "form-checkbox rounded m-1", defaultChecked: body?.retain ?? false }), _jsx("span", { className: "flex flex-col ml-4", children: "Retain Event After Dispatch" })] }), _jsxs("label", { className: `${FORM_GROUP_CLASS} scheduled`, children: [_jsxs("span", { className: "text-gray-700", children: ["Repeat Event on Cron Schedule (", _jsx("a", { href: "https://crontab.guru/", target: "_blank", className: LINK_CLASS, children: "crontab.guru" }), ")"] }), _jsx("input", { className: FORM_CLASS, type: "text", name: "schedule.cron", placeholder: "Cron pattern (0 * * * *)", defaultValue: body?.type || "" }), _jsx("br", {})] }), _jsx("div", { className: "flex flex-col", children: _jsxs("label", { className: FORM_GROUP_CLASS, children: [_jsx("span", { className: "text-gray-700", children: "Include JSON data in event?" }), _jsx("textarea", { name: "data", className: FORM_CLASS, defaultValue: body?.data ?? "" })] }) }), _jsx("div", { id: "action-section", children: _jsx("button", { type: "submit", className: "bg-sky-500 hover:bg-sky-700 px-4 py-2.5 text-sm leading-5 rounded-md font-semibold text-white", children: "Schedule Event" }) })] }));
    }
}
export const Component = ScheduleDurableEvent;
export function fromWebDate(value, timezone) {
    if (!value)
        return undefined;
    let date;
    if (/^\d{4}-\d{2}-\d{2}$/.test(value)) {
        date = DateTime.fromFormat(value, "yyyy-MM-dd", { zone: timezone || DEFAULT_TIMEZONE }).toJSDate();
    }
    else {
        date = DateTime.fromJSDate(new Date(value), { zone: timezone || DEFAULT_TIMEZONE }).toJSDate();
    }
    // Use a consistent format
    return date.toISOString();
}
//# sourceMappingURL=schedule.js.map