// var qqgamesdk = require('qqgamesdk');
var qqgamesdk = require('qqgame-sdk-0.4.2.min');
window.qqNetwork = {};

// load sdk
qqNetwork.qqSdkInitFlag = false;
if (!cc.sys.isNative) {

}

qqNetwork.room2Game = {
    channelCreated: "channelCreated", // 通道创建，大厅到游戏
    gameData: "gameData", // 数据传输，游戏到大厅或者大厅到游戏
    frameData: "frameData",
    gameStart: "gameStart", // 游戏开始，大厅到游戏
    network: "network",
    leave: "leave",
    voice: "voice",
    gameReset: "gameReset",// 游戏重置，大厅到游戏


    gameEnd: 'game_end',//有一端退出？
    playerEnter: 'playerEnter',//玩家从新进入游戏
};

qqNetwork.game2Room = {
    gameInit: "gameInit", // 游戏初始化，游戏到大厅
    gameData: "gameData", // 游戏数据传输，游戏到大厅或者大厅到游戏
    gameReady: "gameReady", // 游戏ready，游戏到大厅
    gameResult: "gameResult", //结算信息，游戏到大厅
    frameData: "frameData",
    leave: "leave", // 退出，游戏到大厅

};

qqNetwork.msgProcess = function (msgName, msgData) {

    if (typeof msgData === "string") {
        if (msgData != "gameStart") {
            msgData = JSON.parse(msgData);
        }

    }

    switch (msgName) {
        case qqNetwork.room2Game.channelCreated:


            var paramFlag1 = false;
            var paramFlag2 = false;
            if (msgData.playerInfos[0].headurl && msgData.playerInfos[0].headurl.indexOf("?") !== -1) {
                paramFlag1 = true;
            }

            if (msgData.playerInfos[1].headurl && msgData.playerInfos[1].headurl.indexOf("?") !== -1) {
                paramFlag2 = true;
            }

            msgData.playerInfos[0].headurl = decodeURI(msgData.playerInfos[0].headurl);
            msgData.playerInfos[1].headurl = decodeURI(msgData.playerInfos[1].headurl);
            if (paramFlag1) {
                msgData.playerInfos[0].headurl = msgData.playerInfos[0].headurl + "&aa=aa.jpg";
            } else {
                msgData.playerInfos[0].headurl = msgData.playerInfos[0].headurl + "?aa=aa.jpg";
            }

            if (paramFlag2) {
                msgData.playerInfos[1].headurl = msgData.playerInfos[1].headurl + "&aa=aa.jpg";
            } else {
                msgData.playerInfos[1].headurl = msgData.playerInfos[1].headurl + "?aa=aa.jpg";
            }

            this.ChannelData = msgData;
            this.isHasChannelData = true;
            // console.log('channelCreated', msgData)
            // if(this.InitIndex == 0){
            // qqNetwork.send(qqNetwork.game2Room.gameReady, {});
            // }
            // this.InitIndex = 1;
            break;

        case qqNetwork.room2Game.gameReset:
            console.log("aNetLib 重置游戏");
            // qqNetwork._init();
            // var NetworkSocket = cc.find('Hero').getComponent("NetworkSocket");
            // NetworkSocket.startGame();
            this.isHasChannelData = false;
            this.send(qqNetwork.game2Room.gameInit);//{ openFraming: 1, fpsExpect: 5 }
            cc.director.loadScene("camera_Mutiplayers");
            break;

    }

    if (this.msgCb) this.msgCb(msgName, msgData);
};

qqNetwork._init = function () {
    this.qqSdkInitFlag = true;

    if (this.debugFlag) {
        return;
    }
    // console.log('EnterInitFunction');
    if (window.qqgame) {
        // console.log('QQ Init');
        window.qqgame.onMessage(function (msgName, msgData) {
            this.msgProcess(msgName, msgData)
        }.bind(this));
    }

    //游戏开始gameInit
    this.isHasChannelData = false;
    this.send(this.game2Room.gameInit);//{ openFraming: 1, fpsExpect: 5 }
};

qqNetwork.connect = function (ip, port, cb) {
    port = port || 8181;
    // 测试用，正在大厅用不上
    console.log('Socket Connet');
    var socketUrl = port !== 0 ? "ws://" + ip + ":" + port : "ws://" + ip;
    if (this.web_socket) {
        this.web_socket.close();
        this.web_socket = null;
    }

    this.web_socket = new WebSocket(socketUrl);
    // this.web_socket.binaryType = "arraybuffer";

    this.web_socket.onmessage = function (event) {
        var data = JSON.parse(event.data);
        var msgName = data["eID"];
        var msgData = data["ePara"];
        this.msgProcess(msgName, msgData);
        // console.log("receive data:" + event.data);
    }.bind(this);

    this.web_socket.onopen = function (event) {
        cc.log("onopen------------");
        if (cb) cb();
        if (this.msgCb) this.msgCb("online", {});
    }.bind(this);

    this.web_socket.onclose = function (event) {
        cc.log("onclose------------");
        this.web_socket = null;

        if (this.msgCb) this.msgCb("offline", {});
    }.bind(this);

    this.web_socket.onerror = function (event) {
        cc.log("onerror------------");
        if (this.msgCb) this.msgCb("offline", {});
    }.bind(this);
};

qqNetwork.send = function (reqName, originData) {
    var data = {
        "eID": reqName,
        "ePara": originData,
    };

    // console.log("send data:" + JSON.stringify(data));
    if (!this.debugFlag) {
        if (this.qqSdkInitFlag) {
            window.qqgame.invoke(reqName, originData);
        } else {
            setTimeout(function () {
                this.send(reqName, originData);
            }.bind(this), 200);
        }
    } else {
        if (!this.web_socket) {
            console.error("debug mode need connect websocket");
            return;
        }

        this.web_socket.send(JSON.stringify(data));
    }
};

qqNetwork.enableDebug = function () {
    // this.InitIndex = 0;

    this.debugFlag = false;
    console.log('debugFlag==' + this.debugFlag);
};

qqNetwork.regMsgCallback = function (cb) {
    qqNetwork.msgCb = cb;
};

qqNetwork._init();
// window.network = qqNetwork;