/*
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/util/common.js");
$.getScript("/static/js/util/ajax.js");

/** Adds the listeners on page load (executed in comments.tmpl) */
function initializeNewCommentsClickListener() {

    $("#submitComment").on("click", event => {
        event.preventDefault();

        const value = $("#inputCommentField-New").val();

        if (value)
            sendCommentToServer(event);
    });

    $("#inputCommentField-New").on("input onpropertychange", event => onNewCommentTextAreaChanged($(event.target).val()));
}

/** removes the placeholder from the comments list */
function removeEmptyCommentsLine() {
    $("#commentsEmptyLine").remove();
}

/**
 * This function will be called once the comment field changes
 * @param newValue {string} The new value of the text area
 */
function onNewCommentTextAreaChanged(newValue) {

    // Handle submitButton
    const submitButton = $("#submitComment");
    if (newValue === "")
        submitButton
            .addClass("disabled cursor-not-clickable")
            .attr("data-original-title", "You have to enter text to make a comment");
    else
        submitButton
            .removeClass("disabled cursor-not-clickable")
            .attr("data-original-title", "");

    // Update characters left
    $("#newCommentCharacterLeft").text(1000 - newValue.length)
}

/**
 * Sends a comment to the server
 * @param event
 */
function sendCommentToServer(event) {
    event.preventDefault();
    let inputField = $("#inputCommentField-New");

    $.ajax({
        url: currentURL().toString(),
        type: "PUT",
        data: {
            commentText: inputField.val(),
        }

    }).done(comment => {
        removeEmptyCommentsLine();
        $("#commentListGroup").append(comment);
        $("time.timeago").timeago();
        reloadTooltips();
        inputField.val("");
        onNewCommentTextAreaChanged("")

    }).fail(response => {
    });

}

/**
 * Toggles the edit mode of a comment.
 * @param commentId {string}
 * @param displayEditControls {boolean}
 */
function toggleCommentEditMode(commentId, displayEditControls) {

    if (displayEditControls) {
        $(`#commentTextZone-${commentId}, #commentStartEditButton-${commentId}`).addClass("d-none");
        $(`#commentEditZone-${commentId}`).removeClass("d-none");
    } else {
        $(`#commentTextZone-${commentId}, #commentStartEditButton-${commentId}`).removeClass("d-none");
        $(`#commentEditZone-${commentId}`).addClass("d-none");
    }
}

/**
 * Starts the comment edit mode (when comment is in default mode and edit button was pressed).
 * @param commentId - Unique comment identifier
 */
function startCommentEditMode(commentId) {
    onEditedCommentTextChanged(commentId);
    toggleCommentEditMode(commentId, true)
}

/**
 * Aborts the comment edit mode (when comment is in edit mode and abort button was pressed).
 * @param commentId - Unique comment identifier
 */
function abortCommentEditMode(commentId) {
    toggleCommentEditMode(commentId, false);
    $(`#inputCommentField-${commentId}`).val($(`#comment-original-${commentId}`).text())
}

/**
 * Finishes the comment edit mode (when comment is in edit mode and save button was pressed).
 * @param button The button which was pressed
 * @param commentId - Unique comment identifier
 */
function saveCommentEdited(button, commentId) {

    if (button.classList.contains("disabled"))
        return;

    $.ajax({

        url: `${currentURL().takeFirstSegments(3)}/comment`,
        type: "PUT",
        data: {
            commentText: $(`#inputCommentField-${commentId}`).val(),
            commentId: commentId
        }

    }).done(response => {


        $(`#list-item-comment-${commentId}`).replaceWith(response);
        $("time.timeago").timeago();
        reloadTooltips();


    }).fail(response => {

    })
}

/**
 * When comment is in edit mode and text was changed.
 * @param commentId - Unique comment identifier
 */
function onEditedCommentTextChanged(commentId) {
    const newText = $(`#inputCommentField-${commentId}`).val();

    if (newText){
        $(`#submitCommentEditedButton-${commentId}`)
            .removeClass("disabled cursor-not-clickable")
            .attr("data-original-title", "")
    } else {
        $(`#submitCommentEditedButton-${commentId}`)
            .addClass("disabled cursor-not-clickable")
            .attr("data-original-title", "A comment should not be empty!");
    }

    $(`#editCommentCharacterLeft-${commentId}`).text(1000 - newText.length)
}