const storageArea   = browser.storage.local;
const tabsAction    = browser.tabs;
const windowsAction = browser.windows;
const searchBar     = document.getElementById("searchBar");
const errHandler    = document.getElementById("errorZone");
const listZone      = document.getElementById("listZone");
const notFoundText  = document.createTextNode("Search not found...");
const tabImg        = browser.extension.getURL("icons/tab.png");
let hoverTarget     = undefined
let oldElm          = undefined;
let currentWinId    = undefined;
let newWinId        = undefined;
let focusedWinID    = undefined;
let windowIndex     = 0;

function logTabs(tabs) {
    windowIndex = 0;

    tabsAction.query({currentWindow: true, active: true}).then((tab) => {
        focusedWinID = tab[0].windowId;
    }, focusedWinID).then(() => {
        for (let tab of tabs) {
            currentWinId = tab.windowId;
            if (currentWinId == newWinId) {
                createContainer(tab);
            } else {
                if (windowIndex != 0) {
                    var pTag       = document.createElement("P");
                    var msg        = (focusedWinID == tab.windowId)
                    ? "[  Current Window  ] " : "Window: " + tab.windowId;
                    var pText      = document.createTextNode(msg);
                    pTag.className = "windowIdHeaders";
                    pTag.appendChild(pText);
                    listZone.appendChild(pTag);
                    windowIndex++;
                    createContainer(tab);
                } else {
                    createContainer(tab);
                    windowIndex = 1;
                }
            }
            newWinId = currentWinId;
        }
    });

    newWinId = undefined;
    scrollToView(800);
}

function createContainer(tab) {
    var template       = document.querySelector('#tabContainerTemplate');
    var clone          = document.importNode(template.content, true);
    var spanTag        = clone.querySelector("#iconElm");
    var closeImgTag    = clone.querySelector("#closeBttn");
    var hidnStImgTag   = clone.querySelector("#hideTgglBttn");
    var pTag           = clone.querySelector(".pTagTitleText");
    var icoImgTag      = document.createElement("IMG");  // Used to detect image load failure
    var iconText       = document.createTextNode(tab.title);
    var id             = tab.id;

    // Set oldElm so eventListeners.js has starting ref
    if (tab.active == true) {
        browser.windows.getCurrent().then((window) => {
            if (tab.windowId == window.id) {
                spanTag.className = "block block-focused";
                if (oldElm) {
                    oldElm.setAttribute("class", "block");
                }
                oldElm = spanTag;
            }
        }, tab, oldElm, spanTag);
    }

    spanTag.setAttribute("tabID", tab.id);
    spanTag.title         = tab.title;

    if (!tab.hidden)
        spanTag.className = "block";
    else
        spanTag.className = "block hiddenBGColor";

    spanTag.style.backgroundImage    = "url(" + tab.favIconUrl + ")";
    icoImgTag.src         = tab.favIconUrl;
    icoImgTag.onerror     = function() { spanTag.style.backgroundImage = "url(" + tabImg + ")"; }

    spanTag.addEventListener("mouseenter", function (eve) {
        moveTabControlTo(eve.target);
    });

    pTag.appendChild(iconText);
    listZone.appendChild(clone);
}

function createTab() {
  tabsAction.create({})
            .then(function (tab) {
                createContainer(tab);
            });
}

function createWin() {
  windowsAction.create({});
}

function moveTabControlTo(elm) {
    let tabControls        = document.getElementById("tabControls");
    let hideTgglBttn       = tabControls.querySelector("#hideTgglBttn")
    let rect               = elm.getBoundingClientRect();
    tabControls.style.left = (rect.left - 46) + "px";
    tabControls.style.top  = rect.top + "px";
    hoverTarget            = elm;

    if (elm.className == "block hiddenBGColor")
        hideTgglBttn.src = "../icons/eyeClosed.png";
    else
        hideTgglBttn.src = "../icons/eyeOpen.png";

    tabControls.style.display = "";
}

function onError(error) { console.log(`Error: ${error}`); }

function getTabs() {
    clearNodes(listZone);

    storageArea.get("searchMode").then((results) => {
        var target = document.getElementById("searchMode");
        if (Object.keys(results).length > 0) {
            var fileKeys = Object.keys(results);
            for (let fileKey of fileKeys) {
                var key = results[fileKey];

                if (key) {
                    target.title           = "Searching curent windows...";
                    target.src = "../icons/windows.png";
                    target.setAttribute("searchwindowsmode", true);

                    tabsAction.query({}).then(logTabs, onError)
                                        .then(resetWinIndex, onError);
                } else {
                    target.title           = "Searching curent window...";
                    target.src = "../icons/window.png";
                    target.setAttribute("searchwindowsmode", false);

                    tabsAction.query({currentWindow: true})
                              .then(logTabs, onError);
                }
            }
        } else {
            setSearchMode(target, "curent window", "window", false);
        }
    });
}

async function setSearchMode(target, text, img, state) {
    target.title   = "Searching " + text + "...";
    target.src     = "../icons/" + img + ".png";
    target.setAttribute("searchwindowsmode", state);

    await storageArea.set({"searchMode": state });
    getTabs();  // No loop b/c object keys will be greater than 0 after setup
}

function clearNodes(targetNode) {
    while (targetNode.firstChild) {
        targetNode.removeChild(targetNode.firstChild);
    }
}

function resetWinIndex() {
    windowIndex    = 0;
}

getTabs();
