import apx from "./apx.js";

const autoDeletionBtnElArray = document.querySelectorAll("li.autoDeletionBtn");

autoDeletionBtnElArray.forEach(btn => {
    btn.addEventListener("click", () => {
        autoDeletionBtnElArray.forEach(btn => btn.classList.remove("bg-base-200"));
        btn.classList.add("bg-base-200");
    });
});

document.querySelector("#createThreadBtn").addEventListener("click", async () => {
    const { publicKey, privateKey } = await apx.crypto.genKey();

    const messageObj = await (async (publicKey) => {
        const uuid = crypto.randomUUID();
        const timestamp = Date.now();
        const alias = await apx.crypto.encryptMessage(JSON.parse(localStorage.getItem("apx")).data.headers.xalias, publicKey);

        return {
            privatriid: `${uuid}_${timestamp}`,
            thread: uuid,
            timestamp: timestamp,
            owner: alias,
            title: await apx.crypto.encryptMessage(document.querySelector("#threadNameInput").value, publicKey),
            sender_alias: alias,
            publicKey: publicKey,
            aliases: [
                alias
            ],
            message: await apx.crypto.encryptMessage(document.querySelector("#threadDescriptionInput").value, publicKey),
            dt_autodestruction: (() => {
                const selectedBtn = Array.from(autoDeletionBtnElArray).find(btn => btn.classList.contains("bg-base-200"));
                return parseInt(selectedBtn ? selectedBtn.getAttribute("data-auto-deletion") : 0, 10);
            })(),
            urgencydeletion: document.querySelector('input[type="checkbox"].toggle').checked
        };
    })(publicKey);

    // Faire un post sur l'endpoint /privatri
    
    await apx.indexedDB.set("privatri", "threads", { uuid: messageObj.thread, privateKey: privateKey });
    await apx.indexedDB.set("privatri", "messages", messageObj);
});