import { TABLE } from "./conf.js";
import { Plan, addLog, getTimeDiff } from "./timezone.js";

function showModal() {
    document.querySelector('.modal').style.display = 'flex';
}
function renderLogs(logs) {
    const container = document.getElementById('logContainer');
    container.innerHTML = logs
        .map(log => `<div class="log-item">[${log.time}] ${log.message}</div>`)
        .join('');
    container.scrollTop = container.scrollHeight;
}
function onclick(e) {
    e.preventDefault();
    showModal();
    const btn = e.currentTarget;
    disableButton(btn);

    const boxes = document.querySelectorAll("input[name='option']:checked");
    boxes.forEach((box) => {
        const { name, uri, params } = TABLE[box.value.toUpperCase()];
        // const row = box.closest(".form-row");
        // const fromInput = row.querySelector("input[name='fromDate']");
        // const toInput = row.querySelector("input[name='toDate']");
        // const period = [fromInput.value, toInput.value];

        // const period = ['2025-01-01', '2025-02-01'];
        const plan = new Plan(null, params).get();
        if (plan.period === undefined) {
            addLog(`${name} 未到指定时间`, true);
            return;
        }
        // Deprecated
        const diff = getTimeDiff(plan.period[1], 1);
        if (-12 < diff && diff < 0) {
            const select = confirm("时间未到, 是否确认继续");
            if (!select) return;
        }
        chrome.storage.local.get(['isRunning'], ({ isRunning }) => {
            if (!isRunning) {
                chrome.runtime.sendMessage({ type: "run", data: { plan, uri } });
            }
        });
    });
}
const enableButton = (btn) => {
    btn.disabled = false;
    btn.style.backgroundColor = "#007bff";
    btn.style.cursor = "pointer";
}
const disableButton = (btn) => {
    btn.disabled = true;
    btn.style.backgroundColor = "gray";
    btn.style.cursor = "default";
}
window.onload = function () {
    document.querySelector('.close').addEventListener('click', () => {
        document.querySelector('.modal').style.display = 'none';
    });
    const btn = document.querySelector(".confirm");
    chrome.storage.local.get(['isRunning', 'logs'], ({ isRunning = false, logs = [] }) => {
        if (isRunning) {
            disableButton(btn);
        } else {
            enableButton(btn);
        }
        showModal();
        renderLogs(logs);
    });
    document.querySelector('.cancel').addEventListener('click', () => {
        chrome.storage.local.set({ isRunning: false, logs: [] });
        chrome.runtime.sendMessage({ type: "resetTaskNum" });
        enableButton(btn);
    });
    chrome.runtime.onMessage.addListener((msg) => {
        if (msg.type === 'progress') {
            renderLogs(msg.logs);
        }
    });
    btn.addEventListener("click", onclick);
}
