/*
This file is part of SystemTestPortal.
Copyright (C) 2017  Institute of Software Technology, University of Stuttgart

SystemTestPortal is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

SystemTestPortal is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with SystemTestPortal.  If not, see <http://www.gnu.org/licenses/>.
*/

var settingsTabMapping = Object.freeze({
    project: {name: "project", url: "project"},
    permission: {name: "permission", url: "permission"},
});

/** Add click listeners to tabs and project image */
function initializeSettingsTabListener() {

    // Settings
    $("#projectSettingsSelect").on("click", event => {
        event.preventDefault();
        requestSettingsTab(settingsTabMapping.project);
    });

    // Permissions
    $("#permissionSettingsSelect").on("click", event => {
        event.preventDefault();
        requestSettingsTab(settingsTabMapping.permission);
    });

}

/**
 * Requests a settings tab from the settings subsection menu
 * @param settingsTab
 */
function requestSettingsTab(settingsTab) {

    const nav = currentURL().takeFirstSegments(4)
        .appendSegment(settingsTab.url)
        .appendSegment("async")
        .appendSegment("nav")
        .toString();
    const tab = currentURL().takeFirstSegments(4)
        .appendSegment(settingsTab.url)
        .appendSegment("async")
        .appendSegment("tab")
        .toString();

    let nNav, nTab;

    $.when(

        $.get(nav, response => {
            nNav = response
        }),
        $.get(tab, response => {
            nTab = response
        })

    ).then(

        // Successful
        () => {
            history.pushState('data', '', currentURL().removeLastSegments(1).appendSegment(settingsTab.url).toString());
            $("#settings-nav").empty().append(nNav);
            $("#settings-tab").empty().append(nTab);
        },

        // On fail reload page -> an error will be shown
        () => {
            window.location.href = currentURL()
        }
    );

}