/*
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/>.
*/

/**
 * Ajax Request to a target with params. It changes the browser history to the target.
 * @param event
 * @param target must be an already URL-encoded string
 * @param params
 * @param requestType
 */
function ajaxRequestFragment(event, target, params, requestType) {
    ajaxRequestFragmentWithHistory(event, target, params, requestType, target);
}

/**
 * Ajax Request to a target with params. It changes the browser history to the historyText parameter.
 * Will display a new tab fragment.
 * @param event
 * @param target must be an already URL-encoded string
 * @param params
 * @param requestType
 * @param historyText
 */
function ajaxRequestFragmentWithHistory(event, target, params, requestType, historyText) {
    event.preventDefault();

    const newTarget = updateQueryStringParameter(encode(target), "fragment", true);

    // sends the ajax request
    $.ajax({

        url: newTarget,
        type: requestType,
        data: params

    }).done(response => {

        window.history.pushState("data", "", historyText);
        $("#tabarea").empty().append(response);
        $(() => $("[data-toggle='tooltip']").tooltip());

        return true;

    }).fail(response => {

        $("#modalPlaceholder").empty().append(response.responseText);
        $("#errorModal").modal("show");

    });
}

/**
 * Prepares the ajax request target
 * @param target
 * @returns {string}
 */
function encode(target) {

    const index = target.lastIndexOf("?");
    let params = "";
    if (index !== -1) {
        target = target.substr(0, index);
        params = target.substr(index + 1, target.length);
    }

    const uri = target.split("/");
    for (let i = 0; i < uri.length; i++) {
        uri[i] = encodeURIComponent(uri[i]);
    }

    return uri.join("/") + params;
}

/**
 * prepares the URL with the parameters
 * @param uri
 * @param key
 * @param value
 * @returns {*}
 */
function updateQueryStringParameter(uri, key, value) {

    const regex = new RegExp("([?&])" + key + "=.*?(&|#|$)", "i");
    if (uri.match(regex))
        return uri.replace(regex, "$1" + key + "=" + value + "$2");

    const index = uri.lastIndexOf('#');
    let hash = "";
    if (index !== -1) {
        hash = uri.slice(index, uri.length);
        uri = uri.slice(0, index);
    }
    const separator = uri.indexOf('?') !== -1 ? "&" : "?";

    return uri + separator + key + "=" + value + hash;
}

/**
 * Ajax Request sends data to the server.
 * @param event
 * @param target
 * @param paramData
 */
function ajaxSendDataToServer(event, target, paramData) {
    event.preventDefault();

    $.ajax({
        url: target,
        type: "PUT",
        data: paramData
    })
}

/**
 * Requests a tab by name
 * @param event the event which requests the new tab
 * @param tab {tabMapping} new tab to request
 * @returns {boolean} whether request was executed
 */
function requestTab(event, tab) {

    const targetClassList = event.target.classList;
    if (targetClassList.contains("Warning-On-Current-Action-Abort-Active") || targetClassList.contains("disabled"))
        return false;

    event.preventDefault();

    const segmentNumber = 3;
    const url = currentURL();

    const requestURL = url.takeFirstSegments(segmentNumber).appendSegment(tab.url).toString() + "/";
    const posting = (tab.name === "testcases" || tab.name === "testsequences")
        ? $.get(requestURL + "?fragment=true&filter=" + JSON.stringify(getFilterFromSession()))
        : $.get(requestURL + "?fragment=true");

    posting.done(response => {

        if (url.segments[segmentNumber] !== tab.name || url.segments[segmentNumber + 1] !== "")
            history.pushState('data', '', requestURL);

        $("#modalPlaceholder").empty();
        $('#tabarea').empty().append(response);

        updateTabs(tab.name);
        updateMenu(tab.name);

    }).fail(response => {
        $("#modalPlaceholder").empty().append(response.responseText);
        $('#errorModal').modal('show');
    });

    return true;
}