/**
 * Created by zzsun on 15-1-29.
 */


var SocketServer = {
    //"url":  "ws://192.168.62.202:9980",
//    "url": "ws://192.168.62.156:9980",
     "url":  "ws://localhost:9980",
    "testUrl": "ws://localhost:9980/test"
};

var WS, id = 1, _that;
var WebScoketClient = require('websocket').w3cwebsocket;
/*var fs = require('fs');
var path = require('path');
var _path = path.resolve("./");
console.error(_path);
function shelllog(msg) {
    fs.appendFile(_path + "/log.txt", '\r\n ------' + new Date() + ':' + msg, function () {
    });
}*/

var TAWebSocket = function () {
    this.SocketCreated = false;
    this.isUserloggedout = false;
    this.TA_APP_ID = null;
};

TAWebSocket.prototype.init = function (ID) {
    console.error(ID)
    _that = this,

        WebSocketsExist = true;
    try {
        new WebScoketClient(SocketServer.testUrl);
    } catch (ex) {
        WebSocketsExist = false;
    }
    if (WebSocketsExist) {
        console.error("您的浏览器支持WebSocket. 您可以尝试连接到聊天服务器!", "OK");
        _that.run(ID);
    } else {
        console.error("您的浏览器不支持WebSocket。请选择其他的浏览器再尝试连接服务器。", "ERROR");
    }

};

TAWebSocket.prototype.run = function (ID) {
    var that = this;
    if (!that.SocketCreated && !WS) {
        try {
            WS = new WebScoketClient(SocketServer.url);
            _that.SocketCreated = true;
            _that.isUserloggedout = false;
            _that.TA_APP_ID = ID;
            WS.onopen = _that.onOpen;
            WS.onmessage = function (event) {
                if (_that._onReceive) {
                    _that._onReceive.call(_that._context, event);
                }
            };
            WS.onclose = _that.onClose;
            WS.onerror = _that.onError;
        } catch (ex) {
            console.error(ex);
            return;
        }
    }

};

TAWebSocket.prototype.onOpen = function () {
    var sendJson = {
        type: 'conn',
        action: 'register',
        from: _that.TA_APP_ID || '',
        to: 'all',
        id: id++,
        data: 'login'
    };
    WS.send(JSON.stringify(sendJson));
};

TAWebSocket.prototype.send = function (json) {
    var sendJson;
    if (json) {
        sendJson = {
            type: json.type || 'logic',
            action: json.action || '',
            from: _that.TA_APP_ID || '',
            to: json.to || 'all',
            id: id++ || 1,
            data: json.data || ''
        };
        try{
            WS.send(JSON.stringify(sendJson));
        }catch (e){ }

    }
};


TAWebSocket.prototype.onReceive = function (event) {

    console.log("this is a none");
};

TAWebSocket.prototype.onClose = function (evt) {
    _that.SocketCreated = false;
    _that.isUserloggedout = true;
    console.error("远程连接中断");
};

TAWebSocket.prototype.onError = function (evt) {
    console.error("远程连接中断" + evt.data);
};

TAWebSocket.prototype.close = function (evt) {
    WS.close();
};


module.exports = TAWebSocket;
