/***
 * 发送：
 *  _act : string
 *  _tflag: int
 *  else:  string
 *
 * 接收：
 *  _act : string
 *  _tflag:int
 *  code:  int     - 错误码
 *  info:  string  - 错误信息
 *  retData: 返回的数据JSON
 *      {_more : 1 - int 表示还有多的数据，js不会清理掉callback}
 */

var CARDREADER = new function(){
    var cbs = {};
    var connectionCallback = null;
    var _CONNECT = function(data, callback) {
        var _wsImpl = window.WebSocket || window.MozWebSocket;
        if(_wsImpl==null){
            callback({code:700, info:"你的浏览器不支持WebSocket"});
            return;
        }
        if(window.wst != null){
            return;  //TODO 消息入栈
        }
        console.log("connecting...")
        
        // 动态获取当前页面的主机地址
        var host = window.location.hostname || '127.0.0.1';
        var wsUrl = 'ws://' + host + ':17798/';
        console.log('Connecting to WebSocket:', wsUrl);
        window.wst = new _wsImpl(wsUrl);
        //window.wst = new _wsImpl('ws://127.0.0.1:17798/');
        wst.onmessage = function (evt) {
            var rdata = evt.data;
            console.log("收到数据，长度："+rdata.length);
            rdata = eval("rdata="+rdata);
            
            // 检查是否是连接时的欢迎消息或getCapabilities响应
            if (rdata._act === 'welcome' || rdata._act === 'getCapabilities') {
                // 这是连接时服务器发送的欢迎消息或capabilities响应
                if (typeof connectionCallback === 'function') {
                    connectionCallback(rdata);
                }
                // 如果有_tflag，继续正常处理
                if (!rdata._tflag) {
                    return;
                }
            }
            
            var tflag = rdata._tflag;
            delete rdata._tflag;
            // 检查回调函数是否存在
            if(cbs[tflag] && typeof cbs[tflag] === 'function') {
                cbs[tflag](rdata);
                if(rdata.retData==null || rdata.retData._more!= 1)//后续没有数据了
                    delete cbs[tflag];
            } else {
                console.warn("回调函数不存在，tflag: " + tflag);
            }
        };
        wst.onopen = function(){
            console.log("connected!!")
            window.ws = wst;
            delete window.wst;
            if(data==null) return;
            _SEND(data, callback);
            data = null;
            callback = null;
        }
        wst.onerror = function(error) {
            console.log("WebSocket error:", error);
            // 连接错误时更新状态
            if (typeof updateConnectionStatus === 'function') {
                updateConnectionStatus(false);
            }
        }
        wst.onclose = function () {
            console.log("closed!!");
            // 更新连接状态为断开
            if (typeof updateConnectionStatus === 'function') {
                updateConnectionStatus(false);
            }
            if(callback!=null) callback({code:701, info:"PC端服务中间件未运行"});
            for(var i in cbs){
                cbs[i]({code:702, info:"PC端服务中间件已关闭"});
                delete cbs[i];
            }
            delete window.ws;
            delete window.wst;
        }
    };

    _SEND = function(data, callback){
        if(window.ws==null){
            _CONNECT(data, callback);
            return;
        }
        var tflag = new Date().getTime()%100000000;
        data._tflag = tflag;
        cbs[tflag] = callback;
        try{
            ws.send(JSON.stringify(data));
        }catch (e) {
            // 发送失败时更新连接状态
            if (typeof updateConnectionStatus === 'function') {
                updateConnectionStatus(false);
            }
            callback({code:700, info:"PC端服务中间件未运行"});
        }
    };

    this.send = function(data, callback){
        //data = JSON.stringify(data);
        showMsg("<span style='color:darkgreen;'>发送数据：" + JSON.stringify(data)+"</span>");
        _SEND(data, callback);
    }
    
    this.setConnectionCallback = function(callback) {
        connectionCallback = callback;
    }
};
