/*
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 initializeCommentsClickListener() {

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

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

        if (value) {
            sendCommentToServer(event);
            addCommentToList();
            removeEmptyCommentsLine();
            onNewCommentTextAreaChanged("")
        }
    });

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

/** removes the placeholder from the comments list */
function removeEmptyCommentsLine() {
    if ($("#commentListGroup .list-group-item").length === 1)
        document.getElementById("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(250 - newValue.length)
}

/**
 * Displays a comment in the front end list.
 */
function addCommentToList() {

    const commentList = $("#commentListGroup");
    const commentAmount = commentList.find("li").length;

    const commentField = $("#inputCommentField");
    const newCommentText = commentField.val();
    commentField.val("");

    const author = document.getElementById("userMenu").innerText;

    parseMarkdown(newCommentText).done(html => {
        commentList.append(
            `<li class="list-group-item">
            <div id="comment-${commentAmount}" class="comment row">
                <div class="col-sm-2">
                    <label for="commentText-${commentAmount}" id="commentLabel-${commentAmount}">${author}</label>
                </div>
                <div class="col-sm-10">
                    <span id="commentText-${commentAmount}">${html}</span>
                </div>
            </div>
        </li>`
        );
    })

}

/**
 * Sends a comment to the server
 * @param event
 */
function sendCommentToServer(event) {

    $.ajax({
        url: currentURL().toString(),
        type: "PUT",
        data: {
            commentText: $("#inputCommentField").val()
        }
    }).done(function (response) {
        return true;
    }).fail(function (response) {
        return true;
    });

}