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

/** Sets up all buttons on the permission tab pane and nav bar. */
function initializePermissionSettingsListener() {

    $('#SavePermissionsButton').on("click", () => savePermissionSettings());

    $("#addRoleButton").on("click", () => addNewRoleEntry());

    $(".buttonDeleteRole").on("click", event => deleteRoleConfirm(event));

    $(".buttonDeleteRoleConfirm").on("click", event => deleteRole(event));

}

/** Will send a PUT request to store all (old & new) permissions. */
function savePermissionSettings() {

    let emptyNameFound = false;

    $("#rolesList form[id]").each((idx, form) => {

        if (!$(form)[0].checkValidity()) {
            $(form)[0].reportValidity();
            emptyNameFound = true;
        }
    });

    if (!emptyNameFound) {
        $.ajax({

            url: currentURL().toString() + "/roles",
            type: "PUT",
            data: JSON.stringify(getPermissionSettingsParams())

        }).done(() => {

            globalVarOldRoles = getRolesNameList();
            location.replace(location.pathname);

            return true;

        }).fail(response => {

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

        });
    }
}

/** Fetches the permission setting values */
function getPermissionSettingsParams() {

    return {
        Names: getRolesNameList(),
        Permissions: getPermissions(),
    }
}

/**
 * Gets an array of all role names
 * @returns {Array}
 */
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;
}

/**
 * Gets all permissions currently on the board
 * @returns {Array}
 */
function getPermissions() {

    const permissionIdSuffixes = ["_Execute", "_CreateCase", "_EditCase", "_DeleteCase", "_DuplicCase", "_AssignCase",
        "_CreateSeq", "_EditSeq", "_DeleteSeq", "_DuplicSeq", "_AssignSeq",
        "_EditMembers", "_EditProj", "_DeleteProj", "_EditPerm"];

    const amountPermissions = 16;
    const rolePermissions = [];
    let roles = globalVarOldRoles;

    //Add old role permissions (all already existing ones)
    for (let roleNr = 0; roleNr < roles.length; roleNr++) {
        rolePermissions[roleNr] = new Array(amountPermissions);

        const roleName = roles[roleNr].toString();
        for (let roleIdx = 0; roleIdx < amountPermissions - 1; roleIdx++)
            rolePermissions[roleNr][roleIdx] = document.getElementById(`${roleName}${permissionIdSuffixes[roleIdx]}`).checked
        rolePermissions[roleNr][amountPermissions - 1] = true;
    }

    // Add new rolePermissions (new roles' form has an id)
    $("#rolesList form[id]").each(function () {
        const identifier = String(this.id).split("_")[0];

        const newRole = new Array(amountPermissions);
        for (let roleIdx = 0; roleIdx < amountPermissions - 1; roleIdx++)
            newRole[roleIdx] = document.getElementById(`${identifier}${permissionIdSuffixes[roleIdx]}`).checked
        newRole[amountPermissions - 1] = true;

        rolePermissions.push(newRole);
    });

    return rolePermissions
}

/** This function gets called if the "Add New Role" button gets pressed. It will add a new role entry to fill. */
function addNewRoleEntry() {

    const newId = String(Date.now()).hashCode();

    $("#rolesList").prepend(
        `<form id="${newId}_NewForm" class="p-2">

            <h2 class="input-group">
                <input id="${newId}_nameInput" class="form-control roleNameInput" placeholder="Please insert a new name ..." required>
                
                <span class="input-group-btn">
                    <button type="button" class="btn btn-danger float-right" 
                        onclick=" document.getElementById('rolesList').removeChild(document.getElementById('${newId}_NewForm'))">
                        <i class="fa fa-trash-o" aria-hidden="true"> </i>
                        <span class="d-sm-inline">Delete</span>
                    </button>
                </span>
            </h2>

            <div class="card-group pt-2 pb-5">
                <div class="card">
                    <div class="card-body">
                        <h6 class="card-title">Execution</h6>
                        <p class="card-text">
                            <input id="${newId}_Execute" type="checkbox">
                            <label for="${newId}_Execute">Execute</label>
                        </p>
                    </div>
                </div>
                <div class="card">
                    <div class="card-body">
                        <h6 class="card-title">Test Cases</h6>
                        <p class="card-text">
                            <input id="${newId}_CreateCase" type="checkbox">
                            <label for="${newId}_CreateCase">Create</label><br>

                            <input id="${newId}_EditCase" type="checkbox">
                            <label for="${newId}_EditCase">Edit</label><br>

                            <input id="${newId}_DeleteCase" type="checkbox">
                            <label for="${newId}_DeleteCase">Delete</label><br>

                            <input id="${newId}_DuplicCase" type="checkbox">
                            <label for="${newId}_DuplicCase">Duplicate</label><br>

                            <input id="${newId}_AssignCase" type="checkbox">
                            <label for="${newId}_AssignCase">Assign</label>
                        </p>
                    </div>
                </div>
                <div class="card">
                    <div class="card-body">
                        <h6 class="card-title">Test Sequences</h6>
                        <p class="card-text">
                            <input id="${newId}_CreateSeq" type="checkbox">
                            <label for="${newId}_CreateSeq">Create</label><br>

                            <input id="${newId}_EditSeq" type="checkbox">
                            <label for="${newId}_EditSeq">Edit</label><br>

                            <input id="${newId}_DeleteSeq" type="checkbox">
                            <label for="${newId}_DeleteSeq">Delete</label><br>

                            <input id="${newId}_DuplicSeq" type="checkbox">
                            <label for="${newId}_DuplicSeq">Duplicate</label><br>

                            <input id="${newId}_AssignSeq" type="checkbox">
                            <label for="${newId}_AssignSeq">Assign</label>
                        </p>
                    </div>
                </div>
                <div class="card">
                    <div class="card-body">
                        <h6 class="card-title">Members</h6>
                        <p class="card-text">
                            <input id="${newId}_EditMembers" type="checkbox">
                            <label for="${newId}_EditMembers">Edit</label>
                        </p>
                    </div>
                </div>
                <div class="card">
                    <div class="card-body">
                        <h6 class="card-title">Settings</h6>
                        <p class="card-text">
                            <input id="${newId}_EditProj" type="checkbox">
                            <label for="${newId}_EditProj">Edit</label><br>

                            <input id="${newId}_DeleteProj" type="checkbox">
                            <label for="${newId}_DeleteProj">Delete</label><br>

                            <input id="${newId}_EditPerm" type="checkbox">
                            <label for="${newId}_EditPerm">Edit Perm.</label>
                        </p>
                    </div>
                </div>
            </div>
        </form>`
    );
    document.getElementById(`${newId}_nameInput`).focus();

}

/**
 * This function gets called if the delete button gets pressed for the **first** time.
 * @param event
 */
function deleteRoleConfirm(event) {
    event.preventDefault();
    $(event.currentTarget).next().removeClass("d-none");
    $(event.currentTarget).addClass("d-none");
}

/**
 * This function gets called if the delete button gets pressed a **second** time.
 * @param event
 */
function deleteRole(event) {
    event.preventDefault();
    let button = event.currentTarget;
    while (button.nodeName !== "BUTTON") {
        button = button.parentNode;
    }
    deleteRoleRequest(button.id)
}

/**
 * This function gets invoked when the delete button gets pressed a second time.
 * @param role {string}- The role id (currently the name) of the role to delete
 */
function deleteRoleRequest(role) {

    $.ajax({

        url: currentURL().toString() + "/roles/delete",
        type: "DELETE",
        data: JSON.stringify(role)

    }).done(() => {

        location.replace(location.pathname);
        return true;

    }).fail(() => {

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

    });
}