import { xlsx2csv } from "./xlsx.js";
import { createZip, checkResponse } from "./util.js";
import { makeLogEntry } from "./timezone.js";
import { uploadFile } from "./upload.js";

const checkURL = (u1, u2) => {
    if (!u1 || !u2) return false;
    return u1.startsWith(new URL(u2).origin) && !u1.includes("signin");
};
const sendTabMsg = (msg, callback) => {
    const uri = msg.data.uri;
    chrome.tabs.query({}, (tabs) => {
        const tab = tabs.filter(x => checkURL(x.url, uri))[0];
        if (!tab) {
            const errorMsg = `tab not found, msg: ${JSON.stringify(msg)}`
            callback ? callback(errorMsg) : console.error(errorMsg);
            chrome.notifications.create({
                type: "basic",
                title: "插件提醒",
                message: "请重新打开页面!",
                iconUrl: chrome.runtime.getURL('icon.png'),
                requireInteraction: true,
            });
            return;
        }
        console.log(`send ${JSON.stringify(msg)} to ${tab.url}`);
        chrome.tabs.sendMessage(tab.id, msg, (response) => {
            callback ? callback(response) : console.log(response);
        });
    });
}
const tabCache = new Map();
chrome.tabs.onUpdated.addListener(async (tabId, changeInfo, tab) => {
    if (changeInfo.status === "complete" && tab.url) {
        const targets = [
            'https://login.account.wal-mart.com/authorize',
            'https://seller.walmart.com/home'
        ];
        const url = tab.url.split("?")[0];
        if (!targets.includes(url)) return;
        const oldUrl = tabCache.get(tabId);
        if (oldUrl && oldUrl === url) return
        console.log(`trigger ${url}`);
        chrome.tabs.sendMessage(tabId, { type: "jump" });
        tabCache.set(tabId, url);
    }
});
chrome.tabs.onRemoved.addListener((tabId) => {
    tabCache.delete(tabId);
});
async function sopLink(data) {
    let { url, fn } = data;
    console.log(`GET ${url}`);
    let response = await fetch(url);
    console.log(response);
    await checkResponse(response);
    let blob = await response.blob();
    const csv = xlsx2csv(await blob.arrayBuffer(), { type: "array" });
    if (!csv.includes("No data found")) {
        fn = fn.replace(/\.\w+$/g, ".csv");
        const zip = await createZip([csv], [fn]);
        fn = fn.replace(/\.\w+$/g, ".zip");
        const form = new FormData();
        form.append("zipfile", zip, fn);
        await uploadFile(fn, form);
        // downloadFile(fn, zip);
    }
}
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
    (async () => {
        if (msg.type === "run") {
            startTask();
            sendTabMsg(msg, sendResponse);
        } else if (msg.type === "resetTaskNum") {
            clearInterval(taskInterval);
            taskInterval = null, taskNum = 0, logs = [];
            sendResponse();
        } else if (msg.type === "addLog") {
            logs.push(msg.data);
            if (msg.push) {
                chrome.runtime.sendMessage({ type: 'progress', logs });
            }
            sendResponse();
        } else if (msg.type === "executeScript") {
            const results = await chrome.scripting.executeScript({
                target: { tabId: sender.tab.id },
                world: "MAIN",
                func: (wAttr) => {
                    return window[wAttr];
                },
                args: [msg.data]
            });
            sendResponse(results[0].result);
        } else if (msg.type === "sopLink") {
            try {
                await sopLink(msg.data);
                sendResponse({ status: "ok" });
            } catch (err) {
                sendResponse({ status: "error", error: err.message });
            }
        }
    })();
    return true;
});

let taskInterval = null, taskNum = 0, logs = [];
function startTask() {
    taskNum++;
    if (taskInterval) return;
    chrome.storage.local.set({ isRunning: true });
    taskInterval = setInterval(() => {
        // 推送更新
        const ackLen = logs.filter(x => x.message.includes("完成")).length;
        chrome.runtime.sendMessage({ type: 'progress', logs });
        if (ackLen === taskNum) {
            logs.push(makeLogEntry("已全部完成"));
            chrome.runtime.sendMessage({ type: 'progress', logs });
            // copy logs
            chrome.storage.local.set({ isRunning: false, logs });
            clearInterval(taskInterval);
            // recycle
            taskInterval = null, taskNum = 0, logs = [];
        }
    }, 1000);
}
