/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

/*
 * Chat functionality for home page
 */

function initChat() {
    messages = app.messages.create({
        el: '.messages',
        pageContentEl: '#messagebar',

        // First message rule
        firstMessageRule: function (message, previousMessage, nextMessage) {
            // Skip if title
            if (message.isTitle)
                return false;
            /* if:
             - there is no previous message
             - or previous message type (send/received) is different
             - or previous message sender name is different
             */
            if (!previousMessage || previousMessage.type !== message.type || previousMessage.name !== message.name)
                return true;
            return false;
        },
        // Last message rule
        lastMessageRule: function (message, previousMessage, nextMessage) {
            // Skip if title
            if (message.isTitle)
                return false;
            /* if:
             - there is no next message
             - or next message type (send/received) is different
             - or next message sender name is different
             */
            if (!nextMessage || nextMessage.type !== message.type || nextMessage.name !== message.name)
                return true;
            return false;
        },
        // Last message rule
        tailMessageRule: function (message, previousMessage, nextMessage) {
            // Skip if title
            if (message.isTitle)
                return false;
            /* if (bascially same as lastMessageRule):
             - there is no next message
             - or next message type (send/received) is different
             - or next message sender name is different
             */
            if (!nextMessage || nextMessage.type !== message.type || nextMessage.name !== message.name)
                return true;
            return false;
        }
    });
}

function scrollToBottom(id) {
    var div = document.getElementById(id);
    $('#' + id).animate({
        scrollTop: div.scrollHeight - div.clientHeight
    }, 500);
}

function refreshChat(forcescroll) {
    if (typeof forcescroll == 'undefined') {
        forcescroll = false;
    }
    var vars = {
        username: localStorage.getItem("username"),
        password: localStorage.getItem("password")
    };
    if (!(map.getCenter().lng == 0 && Math.abs(map.getCenter().lat) > 0.000001)) {
        vars["latitude"] = map.getCenter().lat;
        vars["longitude"] = map.getCenter().lng;
    }

    // https://stackoverflow.com/a/21067431
    var out = document.getElementById("messages-content");
    // allow 1px inaccuracy by adding 1
    var isScrolledToBottom = out.scrollHeight - out.clientHeight <= out.scrollTop + 1;

    var messagebox = messages;
    callAPI("getchat", vars, function (success) {
        for (var i = 0; i < success.messages.length; i++) {
            var msg = success.messages[i];
            if ($(".message[data-id=" + msg.id + "]").length > 0) {
                continue;
            }
            if (msg.me) {
                messagebox.addMessage({
                    text: msg.message,
                    attrs: {
                        'data-id': msg.id
                    }
                });
            } else {
                messagebox.addMessage({
                    text: msg.message,
                    type: 'received',
                    name: msg.nickname,
                    attrs: {
                        'data-id': msg.id
                    }
                });
            }
        }
        if (isScrolledToBottom || forcescroll) {
            scrollToBottom("messages-content");
        }
    }, function (error) {});
}

function sendChat() {
    var message = $("#chatbox").val().trim();
    var chatfailure = function (error, message) {
        $("#chatbox").prop("disabled", true);
        $("#chatbox").val(error);
        $("#chatbox").addClass("text-color-red");
        setTimeout(function () {
            $("#chatbox").prop("disabled", false);
            $("#chatbox").val(message);
            $("#chatbox").removeClass("text-color-red");
        }, 1000 * 2);
    }
    if (message == "") {
        chatfailure("Message empty.", "");
        return false;
    }
    if (map.getCenter().lng == 0 && Math.abs(map.getCenter().lat) < 0.000001) {
        chatfailure("Can't chat without valid location.", message);
        return false;
    }
    callAPI("sendchat", {
        username: localStorage.getItem("username"),
        password: localStorage.getItem("password"),
        latitude: map.getCenter().lat,
        longitude: map.getCenter().lng,
        message: message
    }, function (success) {
        $("#chatbox").val("");
        refreshChat(true);
    }, function (error) {
        chatfailure(error, message);
    });
}

var messagebar = app.messagebar.create({
    el: '#messagebar',
    textareaEl: '#chatbox'
});

$('a.toggle-messages').on('click', function () {
    var contentbox = $("#messagebar #messages-content");
    if (contentbox.hasClass("display-none")) {
        $("#chattoggle-closed").addClass("display-none");
        $("#chattoggle-opened").removeClass("display-none");
        contentbox.removeClass("display-none");
        scrollToBottom("messages-content");
    } else {
        $("#chattoggle-opened").addClass("display-none");
        $("#chattoggle-closed").removeClass("display-none");
        contentbox.addClass("display-none");
    }
});

$("#sendmsgbtn").click(function () {
    sendChat();
});

$("#chatbox").on("keyup", function (evt) {
    if (evt.keyCode == 13) {
        sendChat();
    }
});