const tools = new Map();

/**
 * Get address of Mock Services
 * 
 * @function
 * @name getMockHost
 * @kind function
 * @returns {string}
 */
function getMockHost() {
    return window.location.protocol + "//" + window.location.hostname + ":8097";
}

/**
 * Function called after page is loaded
 * 
 * @function
 * @name init
 * @kind function
 * @returns {void}
 */
function init() {
    
    tools.set("xpath", "tools/xpath.html");
    tools.set("xsd", "tools/xsd.html");
    tools.set("xslt", "tools/xslt.html");
    tools.set("xmlform", "tools/xmlFormatter.html");
    tools.set("jsonform", "tools/jsonFormatter.html");
    tools.set("mock", "tools/mock.html");

    changeActiveTools('XML');
    loadLastPage();
}

/**
 * Function that updates list of tools depending on chosen category
 * 
 * @function
 * @name changeActiveTools
 * @kind function
 * @param {any} activeClass class of elements that have to be shown
 * @param {any} activeCategoryButton class of category button that has to be active
 */
function changeActiveTools(activeCategoryButton) {
    let toolList = document.getElementById("toolList").children;
    let categoryToClass = new Map([["XML",  "xmlTool"],
                                   ["JSON", "jsonTool"],
                                   ["REST", "restTool"]]);
    
    let activeClass = categoryToClass.get(activeCategoryButton.toUpperCase());
    if(activeClass == null) return;

    for (i = 0; i < toolList.length; i++) {
        if (toolList[i].classList.contains(activeClass))
            toolList[i].style.display = "block";
        else
            toolList[i].style.display = "none";
    }

    let categoryList = document.getElementById("menu").children;

    for (i = 0; i < categoryList.length; i++) {
        if (categoryList[i].innerText == activeCategoryButton)
            categoryList[i].classList.add("active");
        else
            categoryList[i].classList.remove("active");
    }
}

/**
 * Function that changes active tool
 * 
 * @function
 * @name changeTool
 * @kind function
 * @param {any} tool
 * @returns {void}
 */
function changeTool(tool) {
    const url = tools.get(tool);
    localStorage.setItem("lastPage", tool);
    document.getElementById("iframe").src = url;
}

/**
 * Function that loads last used tool and sets active category accordingly
 * 
 * @function
 * @name loadLastPage
 * @kind function
 * @returns {void}
 */
function loadLastPage() {
    var lastPage = localStorage.getItem("lastPage");
    if (lastPage == null) {
        lastPage = "xpath";
    }

    switch (lastPage) { // XML category is default.
        case "jsonform":
            changeActiveTools('JSON');
            break;
        case "mock":
            changeActiveTools('REST');
            break;
                    
    }
    document.getElementById("iframe").src = tools.get(lastPage);
}