import apx from "./apx.js";
import { getOldestPrivatriids } from "./utils.js";

const bodyEl = document.querySelector("body");
const threadNameInputEl = document.querySelector("#threadNameInput");
const autoDeletionBtnElArray = document.querySelectorAll("li.autoDeletionBtn");
const applyModificationsBtnEl = document.querySelector("#applyModificationsBtn");

const displayToastAlert = async (message) => {
    let toastAlertTemplate = "";

    await fetch("./toastAlert.mustache")
        .then(res => res.text())
        .then(template => {
            toastAlertTemplate = template;
        });

    return Mustache.render(toastAlertTemplate, { message });
};

let messageObj = {};

(async () => {
    const params = new URLSearchParams(window.location.search);
    const uuid = params.get("uuid");

    const privateKey = (await apx.indexedDB.get("privatri", "threads", uuid)).privateKey;
    
    const privatriidArray = await getOldestPrivatriids("privatri", "messages");
    let ownerAlias = "";
    
    privatriidArray.forEach(async privatriid => {
        if (privatriid.split("_")[0] === uuid) {
            messageObj = await apx.indexedDB.get("privatri", "messages", privatriid);
            ownerAlias = messageObj.owner;
            
            threadNameInputEl.value = (await apx.crypto.decryptMessage(messageObj.title, privateKey)).data;

            (Array.from(autoDeletionBtnElArray).find(el => el.getAttribute("data-auto-deletion") === String(messageObj.dt_autodestruction))).classList.add("bg-base-200");
        
            if (messageObj.urgencydeletion === true) {
                document.querySelector('input[type="checkbox"].toggle').checked = true;
            };
        };
    });

    applyModificationsBtnEl.addEventListener("click", async () => {
        if (JSON.parse(localStorage.getItem("apx")).data.headers.xalias === (await apx.crypto.decryptMessage(ownerAlias, privateKey)).data) {
            messageObj.title = await apx.crypto.encryptMessage(threadNameInputEl.value, privateKey);
            messageObj.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);
            })();
            messageObj.urgencydeletion = document.querySelector('input[type="checkbox"].toggle').checked;

            await apx.indexedDB.set("privatri", "messages", messageObj);
        } else {
            bodyEl.insertAdjacentHTML("beforeend", await displayToastAlert("You don't have the permissions to edit this thread."));

            setTimeout(() => {
                bodyEl.lastElementChild.remove();
            }, 3000);
        };
    });
})();

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