"use strict";
cc._RF.push(module, '280c3rsZJJKnZ9RqbALVwtK', 'HelloWorld');
// Script/HelloWorld.js

"use strict";

cc.Class({
    extends: cc.Component,

    properties: {
        statusLabel: cc.Label,
        recvLabel: cc.Label,
        wssCacert: {
            type: cc.Asset,
            default: null
        }
    },

    // use this for initialization
    onLoad: function onLoad() {},

    // called every frame
    update: function update(dt) {},

    clicked: function clicked() {
        this.prepareWebSocket();
    },

    prepareWebSocket: function prepareWebSocket() {
        var _this = this;

        var self = this;
        var statusLabel = this.statusLabel;
        var recvLabel = this.recvLabel;
        // We should pass the cacert to libwebsockets used in native platform, otherwise the wss connection would be closed.
        this._wsiSendBinary = new WebSocket("ws://127.0.0.1:8888");
        this._wsiSendBinary.binaryType = "arraybuffer";
        this._wsiSendBinary.onopen = function (evt) {
            _this.statusLabel.string = 'websocket opened';
        };

        this._wsiSendBinary.onmessage = function (evt) {
            var binary = new Uint16Array(evt.data);
            var binaryStr = 'req  msg:' + evt.data;

            var str = '';
            for (var i = 0; i < binary.length; i++) {
                if (binary[i] === 0) {
                    str += "\'\\0\'";
                } else {
                    var hexChar = '0x' + binary[i].toString('16').toUpperCase();
                    str += String.fromCharCode(hexChar);
                }
            }

            binaryStr += str;
            recvLabel.string = binaryStr;
            statusLabel.string = 'recv message';
        };

        this._wsiSendBinary.onerror = function (evt) {
            statusLabel.string = 'websocket error';
        };

        this._wsiSendBinary.onclose = function (evt) {
            statusLabel.string = 'websocket closed';
            _this._wsiSendBinary = null;
        };

        this.scheduleOnce(this.sendWebSocketBinary, 1);
    },

    sendWebSocketBinary: function sendWebSocketBinary() {
        if (!this._wsiSendBinary) {
            return;
        }
        if (this._wsiSendBinary.readyState === WebSocket.OPEN) {
            this.statusLabel.string = 'websocket send message';
            var buf = "Hello WebSocket from Client";

            var arrData = new Uint16Array(buf.length);
            for (var i = 0; i < buf.length; i++) {
                arrData[i] = buf.charCodeAt(i);
            }

            this._wsiSendBinary.send(arrData.buffer);
        } else {
            this.statusLabel.string = "send error, websocket instance wasn't ready...";
            this.scheduleOnce(function () {
                this.sendWebSocketBinary();
            }, 1);
        }
    }
});

cc._RF.pop();