/*
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 selected = "project";
var oldRoles;

// adds the listeners on page load (exectuted in settings.tmpl)
function initializeSettingsClickListener() {
    //Submit button of settings
    $('#SaveChangesProjectSettingsButton').click(function (event) {
        saveSettings(event)
    });
    // Project delete button
    $('#buttonDeleteProject').click(function (event) {
        deleteProject(event)
    });
    // Export json project button
    $('#ExportJsonProjectButton').click(function (event) {
        exportProject(event)
    });

    $(".buttonDeleteRole").click(function (event) {
       deleteRoleConfirm(event)
    });

    $(".buttonDeleteRoleConfirm").click(function (event) {
        deleteRole(event)
    });

    $('#addRoleButton').click(function (event) {
        addNewRoleLine(event);
    });
    //Handle File Change
    $('input[type=file]').change(function (e) {
        readImageInput(this);
    });
}

// this function deletes the current project.
function deleteProject(event) {
    $("#deleteProject").modal('hide');
    //prevents the default event behaviour
    event.preventDefault();

    //sends delete request to the server
    var path = currentURL().toString();
    var posting = $.ajax({
        url: path,
        type: "DELETE",
        data: ""
    });

    //redirects to the start page or shows error modal
    posting.done(function (response) {
        location.href = "http://" + location.host + "/";
        return true;
    }).fail(function (response) {
        $("#modalPlaceholder").empty().append(response.responseText);
        $('#errorModal').modal('show');
    });
}

// sends the selected settings to the server
function saveSettings(event) {
    var active = $("#v-pills-tab .active").attr("id");
    event.preventDefault();
    if(active === "projectSettingsSelect"){
        saveProjectSettings(event);
    }else if(active === "permissionSettingsSelect"){
        let err = false;
        $(".roleNameInput").each(function () {
            if(this.value === ""){
                err = true
            }
        });
        if(!err){
            savePermissionsSettings(event)
        }else{
            $("#emptyNameModal").modal("show");
        }
    }
}

function saveProjectSettings(event){
    let path = currentURL().toString() + "/";

    event.preventDefault();
    let posting = $.ajax({
        url: path,
        type: "POST",
        data: getProjectSettingsParams()
    });
    posting.done(function (response) {
        location.replace(location.pathname);
        return true;
    }).fail(function (response) {
        $("#modalPlaceholder").empty().append(response.responseText);
        $('#errorModal').modal('show');
    });
}

// fetches the project setting values
function getProjectSettingsParams() {
    return {
        inputProjectName: $('#inputProjectName').val(),
        inputProjectDesc: $('#inputProjectDescription').val(),
        inputProjectLogo: $('#inputProjectImage').attr("src"),
        optionsProjectVisibility: document.querySelector('input[name="optionsProjectVisibility"]:checked').value
    }
}

function savePermissionsSettings(event){
    var path = currentURL().toString() + "/roles";
    event.preventDefault();

    var posting = $.ajax({
        url: path,
        type: "PUT",
        data: JSON.stringify(getPermissionSettingsParams())
    });
    posting.done(function (response) {
        oldRoles = getRolesNameList();
        location.replace(location.pathname);
        $('#permissionSettingsSelect').tab('show');
        return true;
    }).fail(function (response) {
        $("#modalPlaceholder").empty().append(response.responseText);
        $("#errorModal").modal("show");
    });
}

// fetches the permission setting values
function getPermissionSettingsParams() {
    var roleNames = getRolesNameList();
    return {
        Names: roleNames,
        Permissions: getPermissions(roleNames),
    }
}

// processes image upload
function readImageInput(input) {
    function displayWrongFileModal() {
        $('#modal-wrong-file').modal('show');
        $(input).val("");
    }

    function applyImage(image) {
        let reader = new FileReader();
        reader.onload = function (e) {
            $('#inputProjectImage').attr('src', e.target.result);
        };
        reader.readAsDataURL(image);
    }

    if (input.files && input.files[0]) {
        let file = input.files[0];
        if (file.type.startsWith("image"))
            applyImage(file);
        else
            displayWrongFileModal();
    }
}

function saveOldRoles(roles){
    oldRoles = roles
}

// export the project as json
function exportProject(event) {

    let requestURL = currentURL();
    requestURL.appendSegment("export");

    let req = new XMLHttpRequest();
    req.onreadystatechange = handler;
    req.open("POST", requestURL, true);
    req.responseType = "blob";
    req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    req.send('project='+ requestURL.segments[4]);

    function handler() {
        if(this.readyState === this.DONE) {
            let blob = req.response;
            let link = document.createElement('a');
            let currentURL = window.location.href.split("/");
            let filename = currentURL[4] + "-STP_Project";
            link.download = filename + ".json";
            document.body.appendChild(link)
            link.href = window.URL.createObjectURL(blob);
            link.click();
            setTimeout(function () {
                document.body.removeChild(link);
                window.URL.revokeObjectURL(link);
            }, 100);
        }
    }
}

function getRolesNameList(){
    let roleNames = [];
    let index = 0;

    $(".roleName").each(function () {
        if (this.textContent !== "") {
            roleNames[index] = this.textContent;
        }
        index = index + 1;
    });

    $(".roleNameInput").each(function () {
        if (this.value !== "") {
            roleNames[index] = this.value
        }
        index = index + 1;
    });

    return roleNames;
}

function getPermissions(roleNames){
    let roles = oldRoles;
    let index;
    let countNewRoles = roleNames.length - roles.length;
    let rolePermissions = new Array(roles.length + countNewRoles);
    //Add old role permissions
    for (let i=0; i < roles.length; i++){
        rolePermissions[i] = new Array(16);
        rolePermissions[i][0] = document.getElementById(roles[i].toString() + "_Execute").checked;
        rolePermissions[i][1] = document.getElementById(roles[i].toString() + "_CreateCase").checked;
        rolePermissions[i][2] = document.getElementById(roles[i].toString() +"_EditCase").checked;
        rolePermissions[i][3] = document.getElementById(roles[i].toString() +"_DeleteCase").checked;
        rolePermissions[i][4] = document.getElementById(roles[i].toString() + "_DuplicCase").checked;
        rolePermissions[i][5] = document.getElementById(roles[i].toString() + "_AssignCase").checked;
        rolePermissions[i][6] = document.getElementById(roles[i].toString() + "_CreateSeq").checked;
        rolePermissions[i][7] = document.getElementById(roles[i].toString() + "_EditSeq").checked;
        rolePermissions[i][8] = document.getElementById(roles[i].toString() + "_DeleteSeq").checked;
        rolePermissions[i][9] = document.getElementById(roles[i].toString() + "_DuplicSeq").checked;
        rolePermissions[i][10] = document.getElementById(roles[i].toString() + "_AssignSeq").checked;
        rolePermissions[i][11] = document.getElementById(roles[i].toString() + "_EditMembers").checked;
        rolePermissions[i][12] = document.getElementById(roles[i].toString() + "_EditProj").checked;
        rolePermissions[i][13] = document.getElementById(roles[i].toString() + "_DeleteProj").checked;
        rolePermissions[i][14] = document.getElementById(roles[i].toString() + "_EditPerm").checked;
        rolePermissions[i][15] = true;
        index = i + 1;
    }

    //Add new rolePermissions
    for (let j=0; j < countNewRoles; j++){
        rolePermissions[index] = new Array(16);
        rolePermissions[index][0] = document.getElementById(j.toString() + "_Execute").checked;
        rolePermissions[index][1] = document.getElementById(j.toString() + "_CreateCase").checked;
        rolePermissions[index][2] = document.getElementById(j.toString() +"_EditCase").checked;
        rolePermissions[index][3] = document.getElementById(j.toString() +"_DeleteCase").checked;
        rolePermissions[index][4] = document.getElementById(j.toString() + "_DuplicCase").checked;
        rolePermissions[index][5] = document.getElementById(j.toString() + "_AssignCase").checked;
        rolePermissions[index][6] = document.getElementById(j.toString() + "_CreateSeq").checked;
        rolePermissions[index][7] = document.getElementById(j.toString() + "_EditSeq").checked;
        rolePermissions[index][8] = document.getElementById(j.toString() + "_DeleteSeq").checked;
        rolePermissions[index][9] = document.getElementById(j.toString() + "_DuplicSeq").checked;
        rolePermissions[index][10] = document.getElementById(j.toString() + "_AssignSeq").checked;
        rolePermissions[index][11] = document.getElementById(j.toString() + "_EditMembers").checked;
        rolePermissions[index][12] = document.getElementById(j.toString() + "_EditProj").checked;
        rolePermissions[index][13] = document.getElementById(j.toString() + "_DeleteProj").checked;
        rolePermissions[index][14] = document.getElementById(j.toString() + "_EditPerm").checked;
        rolePermissions[index][15] = true;
        index = index + 1;
    }

    return rolePermissions;
}

function saveOldRoles(roles){
    oldRoles = roles
}

function deleteRoleRequest(role){
    console.log("test");
    console.log(role);
    let path = currentURL().toString() + "/roles/delete";
    let posting = $.ajax({
        url: path,
        type: "DELETE",
        data: JSON.stringify(role)
    });
    posting.done(function (response) {
        location.replace(location.pathname);
        return true;
    }).fail(function (response) {
        //$("#modalPlaceholder").empty().append(response.responseText);
        $("#deleteRoleModal").modal("show");

    });
}

function addNewRoleLine(event){
    event.preventDefault();
    let form;
    let td;
    let input;
    let countNewRoles = $(".roleNameInput").length;
    let table = document.getElementById("rolePermissionTable");
    let row = document.createElement("tr");
    let roleCell = document.createElement("td");
    roleCell.setAttribute("class", "roleCell");
    let roleInput = document.createElement("input");
    roleInput.setAttribute("class", "form-control roleNameInput");
    roleCell.appendChild(roleInput);
    row.appendChild(roleCell);

    td = document.createElement("td");
    form = document.createElement("form");
    input = document.createElement("input");
    input.setAttribute("type", "checkbox");
    input.setAttribute("id", countNewRoles.toString() + "_Execute");
    form.appendChild(input);
    form.appendChild(document.createTextNode(" Execute"));
    td.appendChild(form);
    row.appendChild(td);

    td = document.createElement("td");
    form = document.createElement("form");
    input = document.createElement("input");
    input.setAttribute("id", countNewRoles.toString() + "_CreateCase");
    input.setAttribute("type", "checkbox");
    form.appendChild(input);
    form.appendChild(document.createTextNode(" Create"));
    td.appendChild(form);
    form = document.createElement("form");
    input = document.createElement("input");
    input.setAttribute("id", countNewRoles.toString() + "_EditCase");
    input.setAttribute("type", "checkbox");
    form.appendChild(input);
    form.appendChild(document.createTextNode(" Edit"));
    td.appendChild(form);
    input = document.createElement("input");
    form = document.createElement("form");
    input.setAttribute("id", countNewRoles.toString() + "_DeleteCase");
    input.setAttribute("type", "checkbox");
    form.appendChild(input);
    form.appendChild(document.createTextNode(" Delete"));
    td.appendChild(form);
    form = document.createElement("form");
    input = document.createElement("input");
    input.setAttribute("id", countNewRoles.toString() + "_DuplicCase");
    input.setAttribute("type", "checkbox");
    form.appendChild(input);
    form.appendChild(document.createTextNode(" Duplicate"));
    td.appendChild(form);
    form = document.createElement("form");
    input = document.createElement("input");
    input.setAttribute("id", countNewRoles.toString() + "_AssignCase");
    input.setAttribute("type", "checkbox");
    form.appendChild(input);
    form.appendChild(document.createTextNode(" Assign"));
    td.appendChild(form);
    row.appendChild(td);

    td = document.createElement("td");
    form = document.createElement("form");
    input = document.createElement("input");
    input.setAttribute("id", countNewRoles.toString() + "_CreateSeq");
    input.setAttribute("type", "checkbox");
    form.appendChild(input);
    form.appendChild(document.createTextNode(" Create"));
    td.appendChild(form);
    form = document.createElement("form");
    input = document.createElement("input");
    input.setAttribute("id", countNewRoles.toString() + "_EditSeq");
    input.setAttribute("type", "checkbox");
    form.appendChild(input);
    form.appendChild(document.createTextNode(" Edit"));
    td.appendChild(form);
    form = document.createElement("form");
    input = document.createElement("input");
    input.setAttribute("id", countNewRoles.toString() + "_DeleteSeq");
    input.setAttribute("type", "checkbox");
    form.appendChild(input);
    form.appendChild(document.createTextNode(" Delete"));
    td.appendChild(form);
    form = document.createElement("form");
    input = document.createElement("input");
    input.setAttribute("id", countNewRoles.toString() + "_DuplicSeq");
    input.setAttribute("type", "checkbox");
    form.appendChild(input);
    form.appendChild(document.createTextNode(" Duplic"));
    td.appendChild(form);
    form = document.createElement("form");
    input = document.createElement("input");
    input.setAttribute("id", countNewRoles.toString() + "_AssignSeq");
    input.setAttribute("type", "checkbox");
    form.appendChild(input);
    form.appendChild(document.createTextNode(" Assign"));
    td.appendChild(form);
    row.appendChild(td);

    td = document.createElement("td");
    form = document.createElement("form");
    input = document.createElement("input");
    input.setAttribute("id", countNewRoles.toString() + "_EditMembers");
    input.setAttribute("type", "checkbox");
    form.appendChild(input);
    form.appendChild(document.createTextNode(" Edit"));
    td.appendChild(form);
    row.appendChild(td);

    td = document.createElement("td");
    form = document.createElement("form");
    input = document.createElement("input");
    input.setAttribute("id", countNewRoles.toString() + "_EditProj");
    input.setAttribute("type", "checkbox");
    form.appendChild(input);
    form.appendChild(document.createTextNode(" Edit"));
    td.appendChild(form);
    form = document.createElement("form");
    input = document.createElement("input");
    input.setAttribute("id", countNewRoles.toString() + "_DeleteProj");
    input.setAttribute("type", "checkbox");
    form.appendChild(input);
    form.appendChild(document.createTextNode(" Delete"));
    td.appendChild(form);
    form = document.createElement("form");
    input = document.createElement("input");
    input.setAttribute("id", countNewRoles.toString() + "_EditPerm");
    input.setAttribute("type", "checkbox");
    form.appendChild(input);
    form.appendChild(document.createTextNode(" Edit"));
    td.appendChild(form);
    row.appendChild(td);

    table.appendChild(row);
}

function deleteRole (event){
    event.preventDefault();
    var button = event.currentTarget
    while (button.nodeName !== "BUTTON") {
        button = button.parentNode;
    }
    deleteRoleRequest(button.id)
}

function deleteRoleConfirm(event){
    event.preventDefault();
    $(event.currentTarget).next().removeClass("d-none");
    $(event.currentTarget).addClass("d-none");
}