/**
 * CC Live Chat
 *
 * Created by shanglt on 2017/1/6.
 */
!(function(window, document) {

    var ChatMessageCache = function() {
        this.cache = [];
        this.lastTimeRefresh = new Date().getTime();

        this.INTERVAL_TIME = setInterval(function() {
            chatMessageCache.refresh();
        }, 80);

        this.push = function(data) {
            // 缓存中超过5000条数据，则丢弃
            if (this.cache.length > 5000) {
                return;
            }
            this.cache.push(data);
        };

        this.ableRefresh = function() {
            var n = new Date().getTime();

            if (this.cache.length == 0) {
                return false;
            }

            if ((n - this.lastTimeRefresh) >= 80) {
                return true;
            }
            return false;
        };

        this.refresh = function() {
            if (!this.ableRefresh()) {
                return;
            }

            clearInterval(this.INTERVAL_TIME);

            var d = [];
            var l = Math.min(this.cache.length, 10);
            for (var i = 0; i < l; i++) {
                d.push(this.cache.shift());
            }

            if (typeof on_cc_live_chat_msgs === 'function') {
                on_cc_live_chat_msgs(d);
            }

            this.lastTimeRefresh = new Date().getTime();

            this.INTERVAL_TIME = setInterval(function() {
                chatMessageCache.refresh();
            }, 80);
        };
    };


    var chatMessageCache = new ChatMessageCache();

    window.chat = function(chatLog) {
        chatMessageCache.push({
            username: chatLog.userName,
            msg: chatLog.content
        })
    };

    // 同时开始实时显示聊天信息
    // setInterval(function () {
    //     var ft = 0;
    //     try {
    //         ft = callback.callbackPlayer.getPlayerTime();
    //     } catch (e) {
    //     }
    //     if (ft <= 0) {
    //         return;
    //     }
    //
    //     if (!callback.chatLogs.length) {
    //         return;
    //     }
    //
    //     var chatLog = callback.chatLogs[0];
    //     while (chatLog.time <= ft) {
    //         chatLog = callback.chatLogs.shift();
    //
    //         callback.chatMessageCache.push({
    //             username: chatLog.userName,
    //             msg: chatLog.content
    //         });
    //
    //         if (!callback.chatLogs.length) {
    //             break;
    //         }
    //
    //         chatLog = callback.chatLogs[0];
    //     }
    // }, 1000);

    // json格式解析
    function isJsonObj(str) {
        try {
          if(typeof JSON.parse(str) === 'object') {
            return true
          }
        } catch (e) {
        }
        return false;
    }

    // 接收聊天信息
    function on_cc_live_chat_msgs(datas) {
        var cmHtml = '';
        $.each(datas, function(index, data) {
            if (isJsonObj(data.msg)) {
                data.msg = JSON.parse(data.msg)
                if (data.msg.publish !== 1) {
                    return;
                }
                cmHtml += Template.chatMsg({
                    name: data.username,
                    content: showEm(data.msg.msg)
                });
            } else {
                cmHtml += Template.chatMsg({
                    name: data.username,
                    content: showEm(data.msg)
                });
            }
        });

        var rc = $('#chat-list').children().length - 500 + datas.length;
        if (rc > 0) {
            $('#chat-list> li:lt(' + rc + ')').remove();
        }

        $('#chat-list').append(cmHtml);

        chatScroll();
    }

    var Template = {};
    if ($("#chatMsgTemplate").length) {
        Template.chatMsg = Handlebars.compile($("#chatMsgTemplate").html());
    }
    if ($("#privateChatMsgTemplate").length) {
        Template.privateChatMsg = Handlebars.compile($("#privateChatMsgTemplate").html());
    }

    function chatScroll() {
        $("#chat-list").parent().scrollTop($("#chat-list").height());
    }

    function showEm(str) {
        if (!$.trim(str)) {
            return '';
        }
        str = str.replace(/\</g, '&lt;');
        str = str.replace(/\>/g, '&gt;');
        str = str.replace(/\n/g, '<br/>');

        // TODO 表情目录
        str = str.replace(/\[em_([0-9]*)\]/g, '<img src="./img/em/$1.gif" border="0" />');
        str = str.replace(/\[em2_([0-9]*)\]/g, '<img src="./img/em2/$1.png" border="0" />');

        var nmsg = '';
        $.each(str.split(' '), function(i, n) {
            n = $.trim(n);
            if (n.indexOf('[uri_') == 0 && n.indexOf(']') == n.length - 1 && n.length > 6) {
                var u = n.substring(5, n.length - 1) + ' ';
                nmsg += '<a target="_blank" style="color: #2f53ff" href="' + u + '">' + u + '</a>' + ' ';
            } else {
                nmsg += n + ' ';
            }
        });

        return nmsg;
    }

})(window, document, undefined);