{{/*
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/>.
*/}}
$.getScript("/static/js/project/project-tabs.js");
$.getScript("/static/js/util/ajax.js");
$.getScript("/static/js/project/testprotocols.js");


var dropdown = document.getElementById("versions-dropdown-menu");

var dashboardVariantHeader = document.getElementById("variantNames");

var dashboardContent = document.getElementById("dashboard-content");

var protocols;

function fillDropdown(variants) {
    variants.forEach(function (element) {

        var el = document.createElement("option");
        el.textContent = element.Name;
        el.href = "#";
        dropdown.appendChild(el);
    });
}

function refreshDashboard(dashboardElements, versions, variants, selectedIndex) {
    changeDashboardVersionHeader(versions);
    fillDashboardWithResults(variants, dashboardElements, selectedIndex);
    $('[data-toggle="tooltip"]').tooltip();
}

function refreshDashboard_Sequences(dashboardElements, versions, variants, selectedIndex) {
    changeDashboardVersionHeader_Sequences(versions);
    fillDashboardWithResults_Sequences(variants, dashboardElements, selectedIndex);
    $('[data-toggle="tooltip"]').tooltip();
}

function newSiteDashboard(dashboardElements, versions, variants) {
    changeDashboardVersionHeader(versions);
    fillDashboardWithResults(variants, dashboardElements, 0);
}

function newSiteDashboard_Sequences(dashboardElements, versions, variants) {
    changeDashboardVersionHeader_Sequences(versions);
    fillDashboardWithResults_Sequences(variants, dashboardElements, 0);
}

function onChangeDropdown() {
    dropdown.setAttribute("onchange", "refreshDashboard(dashboardElements, versions, variants, dropdown.selectedIndex)");
}

function onChangeDropdown_Sequences() {
    dropdown.setAttribute("onchange", "refreshDashboard_Sequences(dashboardElements, versions, variants, dropdown.selectedIndex)");
}

function changeDashboardVersionHeader(versions) {

    dashboardVariantHeader.innerHTML = "<th> Test Cases </th>";

    if (variants === null) {
        return;
    }

    versions.forEach(function (element) {
        var el = document.createElement("th");
        el.setAttribute("class", "text-center");
        el.textContent = element.Name;
        dashboardVariantHeader.appendChild(el);
    });
}

function changeDashboardVersionHeader_Sequences(versions) {

    dashboardVariantHeader.innerHTML = "<th> Test Sequences </th>";

    if (variants === null) {
        return;
    }

    versions.forEach(function (element) {
        var el = document.createElement("th");
        el.setAttribute("class", "text-center");
        el.textContent = element.Name;
        dashboardVariantHeader.appendChild(el);
    });
}

function fillDashboardWithResults(variants, dashboardElements, selectedIndex) {
    var variant = variants[selectedIndex];
    var results;

    dashboardElements.forEach(function (element) {
        if (variant.Name === element.Variant.Name) {
            results = element.Results;
        }
    });

    dashboardContent.innerHTML = "";

    results.forEach(function (element) {
        var protocols = element.Protocols;
        var dashboardLine = document.createElement("tr");
        var testCase = document.createElement("td");
        testCase.setAttribute("class", "align-middle testCaseCell");
        testCase.setAttribute("id", element.TestCase.Name.toString());
        testCase.textContent = element.TestCase.Name;
        testCase.onclick = onTestCaseClick;
        dashboardLine.appendChild(testCase);


        var protocolIndex = 0;
        element.Results.forEach(function (result) {
            var el = document.createElement("td");
            var resultIcon;
            el.setAttribute("class", "text-center resultCaseCell");
            el.setAttribute("style", "font-size:1.5em;");
            el.setAttribute("id", element.TestCase.Name.toString() + protocolIndex.toString());
            //Adds click handler for different results
            if (result === 4) {
                resultIcon = initResultIcon(result, null);
                onTestCaseNotApplicableHandler(el, element.TestCase.Name.toString());
                // if the test case is not applicable no protocol is sent
            } else if (protocols[protocolIndex].ProtocolNr === 0) { // required comparison to distinguish between "not assessed" and "not executed"
                resultIcon = initResultIcon(result, null);
                onTestResultClickHandler(el, element.TestCase.Name.toString(), null, true);
                protocolIndex++; // not assessed sends empty protocol
            } else {
                resultIcon = initResultIcon(result, protocols[protocolIndex]);
                onTestResultClickHandler(el, element.TestCase.Name.toString(), protocols[protocolIndex], true);
                protocolIndex++; 
            }

            el.appendChild(resultIcon);

            dashboardLine.appendChild(el);
        });
        dashboardContent.appendChild(dashboardLine);
    });
}

function fillDashboardWithResults_Sequences(variants, dashboardElements, selectedIndex) {
    var variant = variants[selectedIndex];
    var results;

    dashboardElements.forEach(function (element) {
        if (variant.Name === element.Variant.Name) {
            results = element.Results;
        }
    });

    dashboardContent.innerHTML = "";

    var protocolIndex = 0;


    results.forEach(function (element) {
        var protocols = element.Protocols;
        var dashboardLine = document.createElement("tr");
        var testSequence = document.createElement("td");
        testSequence.setAttribute("class", "align-middle testSequenceCell");
        testSequence.setAttribute("id", element.TestSequence.Name.toString());
        testSequence.textContent = element.TestSequence.Name;
        testSequence.onclick = onTestSequenceClick;
        dashboardLine.appendChild(testSequence);


        var protocolIndex = 0;
        element.Results.forEach(function (result) {
            var el = document.createElement("td");
            var resultIcon;
            el.setAttribute("class", "text-center resultSequenceCell");
            el.setAttribute("style", "font-size:1.5em;");
            el.setAttribute("id", element.TestSequence.Name.toString() + protocolIndex.toString());
            //Adds click handler for different results
            if (result === 4) {
                resultIcon = initResultIcon_Sequences(result, null);
                onTestCaseNotApplicableHandler(el, element.TestSequence.Name.toString());
                // if sequence is not applicable no protocol is sent
            } else if (protocols[protocolIndex].ProtocolNr === 0) {
                resultIcon = initResultIcon_Sequences(result, null);
                onTestResultClickHandler(el, element.TestSequence.Name.toString(), null, false);
                protocolIndex++; // not assessed sends empty protocol
            } else {
                resultIcon = initResultIcon_Sequences(result, protocols[protocolIndex]);
                onTestResultClickHandler(el, element.TestSequence.Name.toString(), protocols[protocolIndex], false);
                protocolIndex++;
            }

            el.appendChild(resultIcon);

            dashboardLine.appendChild(el);
        });
        dashboardContent.appendChild(dashboardLine);
    });
}

function initResultIcon_Sequences(result, protocol) {
    var resultIcon = document.createElement("i");
    resultIcon.setAttribute("aria-hidden", "true");
    resultIcon.setAttribute("data-toggle", "tooltip");
    resultIcon.setAttribute("data-placement", "bottom");
    if (result === 0) {
        resultIcon.setAttribute("class", "fa fa-minus-circle text-secondary");
        resultIcon.setAttribute("title", "Test sequence not yet executed");
        if (protocol !== null) {
            resultIcon.setAttribute("class", "fa fa-question-circle text-secondary");
            initTooltip_Sequences(resultIcon, "Not assessed", protocol);
        }
        return resultIcon;
    }

    if (result === 1) {
        resultIcon.setAttribute("class", "fa fa-check-circle text-success");
        resultIcon.setAttribute("title", "Passed");
        initTooltip_Sequences(resultIcon, "Not assessed", protocol);
        return resultIcon;
    }

    if (result === 2) {
        resultIcon.setAttribute("class", "fa fa-exclamation-circle text-warning");
        resultIcon.setAttribute("title", "Passed with comments");
        initTooltip_Sequences(resultIcon, "Not assessed", protocol);
        return resultIcon;
    }

    if (result === 3) {
        resultIcon.setAttribute("class", "fa fa-exclamation-circle text-danger");
        resultIcon.setAttribute("title", "Failed");
        initTooltip_Sequences(resultIcon, "Not assessed", protocol);
        return resultIcon;
    }

    if (result === 4) {
        resultIcon.setAttribute("class", "fa fa-ban text-secondary");
        resultIcon.setAttribute("title", "Test sequence is not applicable for this version");
        return resultIcon;
    }
}

function initResultIcon(result, protocol) {
    var resultIcon = document.createElement("i");
    resultIcon.setAttribute("aria-hidden", "true");
    resultIcon.setAttribute("data-toggle", "tooltip");
    resultIcon.setAttribute("data-placement", "bottom");

    if (result === 0) {
        resultIcon.setAttribute("class", "fa fa-minus-circle text-secondary");
        resultIcon.setAttribute("title", "Test case not yet executed");
        if (protocol !== null) {
            resultIcon.setAttribute("class", "fa fa-question-circle text-secondary");
            initTooltip(resultIcon, "Not assessed", protocol);
        }
        return resultIcon;
    }

    if (result === 1) {
        resultIcon.setAttribute("class", "fa fa-check-circle text-success");
        resultIcon.setAttribute("title", "Passed");
        initTooltip(resultIcon, "Passed", protocol);
        return resultIcon;
    }

    if (result === 2) {
        resultIcon.setAttribute("class", "fa fa-exclamation-circle text-warning");
        resultIcon.setAttribute("title", "Partially Successful");
        initTooltip(resultIcon, "Partially Successful", protocol);
        return resultIcon;
    }

    if (result === 3) {
        resultIcon.setAttribute("class", "fa fa-exclamation-circle text-danger");
        resultIcon.setAttribute("title", "Failed");
        initTooltip(resultIcon, "Failed", protocol);
        return resultIcon;
    }

    if (result === 4) {
        resultIcon.setAttribute("class", "fa fa-ban text-secondary");
        resultIcon.setAttribute("title", "Test case is not applicable for this version");
        return resultIcon;
    }
}

//OnClick listener for testcase cells
function onTestCaseClick(event) {
    $("#tabButtonDashboard").removeClass("active");
    $("#menuButtonDashboard").removeClass("active");

    //Testcase page
    $("#tabButtonTestCases").addClass("active");
    $("#menuButtonTestCases").addClass("active");
    var url = getProjectTabURL().toString().replace("dashboard", "testcases");
    url = url + "/" + event.target.id.toString();
    ajaxRequestFragment(event, url.toString(), "", "GET");
}

//Onclick handler for result cells
function onTestResultClickHandler(element, testName, protocol, isCase) {
    element.addEventListener("click", function (event) {
        if (protocol != null) {
            $('body>.tooltip').remove();
            //Adds right tab highlighting
            $("#tabButtonDashboard").removeClass("active");
            $("#menuButtonDashboard").removeClass("active");
            $("#tabButtonProtocols").addClass("active");
            $("#menuButtonProtocols").addClass("active");

            //links to the test case protocol
            var url = getProjectTabURL().toString().replace("dashboard", "protocols");
            if (isCase) {
                url = url + "/testcases/" + testName;
            } else {
                url = url + "/testsequences/" + testName;
            }
            url = url + "/" + protocol.ProtocolNr.toString();
            ajaxRequestFragment(event, url.toString(), "", "GET");
        } else {
            //if no protocol exists, gives feedback to user
            window.alert("There is no protocol for test: " + testName);
        }
    });
}

//Shows alert for user if test case is not applicable for the version
function onTestCaseNotApplicableHandler(element, testName) {
    element.addEventListener("click", function (event) {
        window.alert("Test: " + testName + " is not applicable for this version");
    });
}

//Shows a tooltip for resultIcons
function initTooltip(resultIcon, result, protocol) {
    var time = new Date(protocol.ExecutionDate).toLocaleString();
    var comment;

    if (protocol.Comment === "") {
        comment = "No comment"
    } else if (protocol.Comment.length > 50) {
        comment = protocol.Comment.substring(0, 49) + "...";
    }else{
        comment = protocol.Comment;
    }
    resultIcon.setAttribute("title", "Result: " + result + "\nTester: " + protocol.UserName.toString() + "\nComment: " + comment + "\nDate: " + time);
}

//Shows a tooltip for resultIcons
function initTooltip_Sequences(resultIcon, result, protocol) {
    var time = new Date(protocol.ExecutionDate).toLocaleString();
    var comment;

    resultIcon.setAttribute("title", "Result: " + result + "\nTester: " + protocol.UserName.toString() + "\nDate: " + time);
}

//Onclick listener for testsequence cells
function onTestSequenceClick(event){
    $("#tabButtonDashboard").removeClass("active");
    $("#menuButtonDashboard").removeClass("active");

    //Testsequence page
    $("#tabButtonTestSequences").addClass("active");
    $("#menuButtonTestSequences").addClass("active");
    var url = getProjectTabURL().toString().replace("dashboard", "testsequences");
    url = url + "/" + event.target.id.toString();
    ajaxRequestFragment(event,url.toString(), "", "GET");
}
