/// <reference path="../references.js" />

rwthapp.util.initNamespace("templates");

rwthapp.templates.supportChat = (function () {

    var userName = null;
    var userMail = null;

    //var supportChannelId = '63b929bd-91ef-4ebd-9fe7-20ed8c6fba7f'; // Dev
    //var supportChannelId = '5567915b-41a2-4683-b778-2679c385cadc'; // Testing
    var supportChannelId = 'e84ea4f1-3886-4ac0-857e-ffb79128d3fe'; // Live

    var load = function (template, parameters) {
        var ids = rwthapp.tokenManager.getStreamIds();
        var date = new Date();
        if (ids != null && ids.length > 0) {
            for (var i = 0; i < ids.length; i++) {
                if (ids[0].timestamp < (date.getTime() - 86400000)) { //86400000 -> 1 day
                    remove();
                    ids = rwthapp.tokenManager.getStreamIds();
                } else {
                    break;
                }
            }
        }
        var idsLength = 0;
        if (ids !== null) {
            idsLength = ids.length;
        }

        return rwthapp.connection.api.das.getMessages(supportChannelId, 'support', 0).then(function (messages) {
            var grouped = groupMessages(messages);
            var openTickets = grouped.support.openCount - grouped.support.closeCount;
            var onlineAgents = 0;
            for (var agentId in grouped.support.agentStatus) {
                if (grouped.support.agentStatus[agentId] === 'online') {
                    onlineAgents++;
                }
            }

            if (onlineAgents == 0) {
                return {
                    template: template,
                    parameters: {
                        chatClosed: true
                    },
                    title: rwthapp.localization.getLocalizedString("supportChat.title")
                };
            }
            else if (openTickets >= onlineAgents * 2) {
                return {
                    template: template,
                    parameters: {
                        chatFull: true
                    },
                    title: rwthapp.localization.getLocalizedString("supportChat.title")
                };
            }
            else {
                if (rwthapp.tokenManager.isLoginPersonalized()) {
                    return rwthapp.connection.api.getUserInfo().then(function (data) {
                        userName = data.FirstName + " " + data.LastName;
                        userMail = data.EMail;
                        return {
                            template: template,
                            parameters: {
                                userName: userName,
                                userMail: userMail,
                                formerStreamIds: ids,
                                formerStreamIdsCount: idsLength
                            },
                            title: rwthapp.localization.getLocalizedString("supportChat.title")
                        };
                    });
                } else {
                    var date = new Date();
                    return {
                        template: template,
                        parameters: {
                            userName: userName,
                            userMail: userMail,
                            formerStreamIds: ids,
                            formerStreamIdsCount: idsLength
                        },
                        title: rwthapp.localization.getLocalizedString("supportChat.title")
                    };
                }
            }
        });
    };

    var ready = function () {
        $('#startChat').click(function () {
            var loggedIn = rwthapp.tokenManager.isLoginPersonalized();
            var displayName = $('#userName').val().trim();
            var email = $('#userMail').val().trim();
            var category = $('#category').val().trim();

            if (displayName === "" || email === "" || category == "") {
                rwthapp.notifications.showToastShort(rwthapp.localization.getLocalizedString("supportChat.insertData"));
                return;
            }
            var streamId = rwthapp.tokenManager.getStreamId();
            var date = new Date();

            var element = {
                streamId: streamId,
                channelId: supportChannelId,
                date: getDate(),
                category: category,
                timestamp: date.getTime()
            };
            var ids = rwthapp.tokenManager.getStreamIds();
            if (ids === null || ids === undefined) {
                ids = [element];
            } else {
                ids.push(element);
            }
            rwthapp.tokenManager.setStreamIds(ids);
            
            return rwthapp.connection.api.das.getMessages(supportChannelId, streamId, null, null)
                .then(function () {
                    return getOpenInfo(category, "RWTHApp");
                })
                .then(function (message) {
                    rwthapp.connection.api.das.sendMessage(message, supportChannelId, 'support', 'support', null, 0);
                    return rwthapp.connection.api.das.sendMessage(message, supportChannelId, 'support', streamId, null, 0);
                })
                .then(function () {
                    return getUserInfo(displayName, email, loggedIn);
                })
                .then(function (message) {
                    return rwthapp.connection.api.das.sendMessage(message, supportChannelId, 'support', streamId, null, 0)
                })
                .then(function () {
                    var infoMessage = {
                        task: 'supportRWTHAppDebugInfo',
                        info: rwthapp.error.generateDebugInformation()
                    };
                    return rwthapp.connection.api.das.sendMessage(JSON.stringify(infoMessage), supportChannelId, 'support', streamId, null, 0);
                })
                .then(function () {
                    rwthapp.navigator.gotoPage('das.channelDetails', { channelId: supportChannelId, streamId: streamId }, true);
                })
                .catch(function (e) {
                    // TODO: redirect to error page
                });
        });
    };

    var getDate = function (category) {
        var date = new Date();
        var ret = "";
        var d = date.getDate();
        ret += ((d < 10) ? "0" + d : d) + ".";
        var m = date.getMonth();
        ret += ((m < 10) ? "0" + m : m) + ".";
        ret += date.getFullYear() + " ";
        var h = date.getHours();
        ret += ((h < 10) ? "0" + h : h) + ":";
        var min = date.getMinutes();
        ret += ((min < 10) ? "0" + min : min) + ":";
        var sec = date.getSeconds();
        ret += ((sec < 10) ? "0" + sec : sec);
        return ret;
    }

    var remove = function () {
        var ids = rwthapp.tokenManager.getStreamIds();
        ids = ids.slice(1);
        rwthapp.tokenManager.setStreamIds(ids);
    }

    var getOpenInfo = function (category, from) {
        var info = {
            task: 'supportOpen',
            category: category,
            sourceUrl: from
        };
        return Promise.resolve().then(function () {
            var message = JSON.stringify(info);
            return message;
        });
    };

    var getUserInfo = function (displayName, email, loggedIn) {
        var info = {
            task: 'supportUserInfo',
            displayName: displayName,
            email: email,
            loggedin: loggedIn
        };
        return Promise.resolve().then(function () {
            var message = JSON.stringify(info);
            return message;
        });
    };

    var groupMessages = function (messages, groupedMessages) {
        groupedMessages = groupedMessages || {};

        for (var i = 0; i < messages.length; i++) {
            var stream = messages[i].stream;
            if (!groupedMessages[stream]) {
                groupedMessages[stream] = {
                    stream: stream,
                    openInfo: null,
                    openCount: 0,
                    userInfo: null,
                    closeInfo: null,
                    closeCount: 0,
                    supporterInfo: null,
                    texts: [],
                    allMessages: [],
                    lastMessage: null,
                    agentStatus: null
                };
            }

            if (messages[i].user == "student") {
                messages[i].isUser = true;
            }

            if (messages[i].type === "support") {
                var supportMessage;
                try {
                    supportMessage = JSON.parse(messages[i].message);
                }
                catch (e) {
                    supportMessage = { task: "supportInvalid" };
                }
                messages[i].supportMessage = supportMessage;

                if (supportMessage.task == 'supportOpen') {
                    groupedMessages[stream].openCount++;
                    groupedMessages[stream].openInfo = messages[i];
                } else if (supportMessage.task == 'supportClose') {
                    groupedMessages[stream].closeCount++;
                    groupedMessages[stream].closeInfo = messages[i];
                } else if (supportMessage.task == 'supportUserInfo') {
                    groupedMessages[stream].userInfo = messages[i];
                } else if (supportMessage.task == 'supportSupporterInfo') {
                    groupedMessages[stream].supporterInfo = messages[i];
                } else if (supportMessage.task == 'supportAgentStatus') {
                    groupedMessages[stream].agentStatus = groupedMessages[stream].agentStatus || {};
                    groupedMessages[stream].agentStatus[supportMessage.id] = supportMessage.status;
                }
            } else {
                groupedMessages[stream].texts.push(messages[i]);
            }
            groupedMessages[stream].allMessages.push(messages[i]);
            groupedMessages[stream].lastMessage = messages[i];
        }

        groupedMessages.support = groupedMessages.support || {};
        groupedMessages.support.agentStatus = groupedMessages.support.agentStatus || {};
        groupedMessages.support.openCount = groupedMessages.support.openCount || 0;
        groupedMessages.support.closeCount = groupedMessages.support.closeCount || 0;

        return groupedMessages;
    }

    return {
        load: load,
        ready: ready
    };
})();