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

const bodyEl = document.querySelector("body");
const aliasListContainerEl = document.querySelector("#aliasListContainer");

let aliasesArray = [];

const newAlias = async (alias) => {
    let aliasTemplate = "";

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

    return Mustache.render(aliasTemplate, { alias });
};

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

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

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

(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");
    
    privatriidArray.forEach(async privatriid => {
        if (privatriid.split("_")[0] === uuid) {
            aliasesArray = (await apx.indexedDB.get("privatri", "messages", privatriid)).aliases;
            const ownerAlias = (await apx.indexedDB.get("privatri", "messages", privatriid)).owner;
            
            for (const alias of aliasesArray) {
                aliasListContainerEl.insertAdjacentHTML("beforeend", await newAlias({
                    decrypted: (await apx.crypto.decryptMessage(alias, privateKey)).data,
                    crypted: alias
                }));
            };

            document.querySelectorAll("button.removeAliasBtn").forEach(btn => {
                btn.addEventListener("click", async () => {
                    if (JSON.parse(localStorage.getItem("apx")).data.headers.xalias === (await apx.crypto.decryptMessage(ownerAlias, privateKey)).data) {
                        if (btn.getAttribute("data-alias") !== ownerAlias) {
                            const alias = btn.getAttribute("data-alias");
                            aliasesArray = aliasesArray.filter(a => a !== alias);
                            btn.parentElement.parentElement.remove();
                
                            privatriidArray.forEach(async privatriid => {
                                if (privatriid.split("_")[0] === uuid) {
                                    const messageObj = await apx.indexedDB.get("privatri", "messages", privatriid);
                                    messageObj.aliases = aliasesArray;
                                    
                                    await apx.indexedDB.set("privatri", "messages", messageObj);
                                };
                            });
                        } else {
                            bodyEl.insertAdjacentHTML("beforeend", await displayToastAlert("You cannot remove the owner of the thread."));

                            setTimeout(() => {
                                bodyEl.lastElementChild.remove();
                            }, 3000);
                        };
                    } else {
                        bodyEl.insertAdjacentHTML("beforeend", await displayToastAlert("You don't have the permissions to remove this alias."));

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

