/*
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");

$("#submitComment").click(function(event) {
    if ($("#inputCommentField").val()) {
        sendCommentToServer(event);
        addCommentToList();
        removeEmptyCommentsLine();
    }
});

$("#inputCommentField").onkeypress = updateCommitButton;

function removeEmptyCommentsLine() {
    var items = $("#commentListGroup").find(".list-group-item");
    if (items.length === 1) {
        document.getElementById("commentsEmptyLine").remove();
    }
}

function updateCommitButton() {
    if (!$("#inputCommentField").val()) {
        $("#submitComment").addClass("disabled");
        $("#submitComment").addClass("not-clickable");
        $("#submitComment").attr("data-original-title", "You have to enter text to make a comment");
    } else {
        $("#submitComment").removeClass("disabled");
        $("#submitComment").removeClass("not-clickable");
        $("#submitComment").attr("data-original-title", "");
    }
}

function addCommentToList() {
    var commentField = $("#inputCommentField");
    var newCommentText = commentField.val();
    commentField.val("");

     var emptyComment = $("#emptyComment").find(".list-group-item");
     emptyComment = emptyComment.clone(true, true);
    var commentText = $(emptyComment).find("p");
    $(commentText)[0].innerHTML = newCommentText;
    var commentLabel = $(emptyComment).find("label")[0];
    var userMenu = document.getElementById("userMenu");
    $(commentLabel).text(userMenu.innerText);

    var ind = $("#commentListGroup").find("li").length;
    emptyComment[0].id = "comment" + ind;

    if (ind > 0) {
        $(".comment").first().before(emptyComment);
    } else {
        $("#commentListGroup").prepend(emptyComment);
    }
}

function sendCommentToServer(event) {
    event.preventDefault();
    var path = currentURL().toString();
    var posting = $.ajax({
        url: path,
        type: "PUT",
        data: {
            commentText: $("#inputCommentField").val()
        }
    });
    posting.done(function (resposne) {
        return true;
    }).fail(function (response) {
        return true;
    });

}