/**
 * 话题推送
 * Copyright (c) 2019 xiaofanku
 * mail:xiaofanku@live.cn
 */
(function($) {
    'use strict';
    var threadSock, config;
    var dtd = $.Deferred();
    //初始化sock
    function init(dtd){
        threadSock = new SockJS(config.remote);
        threadSock.onopen = function() {
            //ETC
            console.log('Thread Socket opened!');
            dtd.resolve();
         };
         
         threadSock.onmessage = function(e) {
             var fn = window[config.callFunctionExp];
             if (typeof fn === "function"){
                 fn.call(this, e.data);
             }
         };
         
         threadSock.onclose = function() {
             console.log('Thread Socket close');
         };
         
         threadSock.onerror = function(e) {
             console.log('Thread Socket has Error: '+e);
             dtd.reject();
         };
         return dtd;
    };
    //版块最新的话题
    var getBoardUpdateTopic = function(board, previousUx){
        threadSock.send('{"id":"'+board+'", "ux":"'+previousUx+'", "cmd":"1"}');
    };
    //话题最近的回复
    var getTopicUpdatePosts = function(topic, previousUx){
        threadSock.send('{"id":"'+topic+'", "ux":"'+previousUx+'", "cmd":"2"}');
    };
    //周期的发送查询请求
    function loopSendRequest(loopUnit){
        setInterval(function(){
            var tux = config.jqEle.attr('data-ux');
            var serialId = config.serial;
            if(config.module === 'board'){
                getBoardUpdateTopic(serialId, tux);
            }
            if(config.module === 'topic'){
                getTopicUpdatePosts(serialId, tux);
            }
        }, loopUnit); //毫秒
    };
    //Jquery绑定
    $.fn.threadSocket = function(option, loopUnit) {
        var _self=this;
        //module:,callFunctionExp:,serial:
        config = $.extend({jqEle: _self, eleId: _self.attr('id')}, option);
        //初始化sock
        $.when(init(dtd)).done(function(){
            loopSendRequest(loopUnit);
        }).fail(function(){ 
            console.log("Thread Socket happed fail"); 
        });
        return this;
    };
})(jQuery);