var KBEngine = require("kbengine");

cc.Class({

    // // 类名，用于序列化
    // // 值类型：String
    // name: "StartScene",

    // 基类，可以是任意创建好的 cc.Class
    // 值类型：Function
    extends: cc.Component,

    // 属性定义（方式一，直接定义）
    properties: {
        clientVersion: null,
        clientScriptVersion: null,
        serverVersion: null,
        serverScriptVersion: null,
        serverVersionLabel: null,
        serverScriptVersionLabel: null,
        debug: null,
        logintButton: cc.Button,
        reloginCount: 0,
    },

    onLoad: function () {

        // 初始化KBEngine
        var args = new KBEngine.KBEngineArgs();

        // 设置登录ip地址
        args.ip = LOGIN_BY_IP ? SERVER_IP : SERVER_URL;
        args.port = SERVER_PORT;
        args.isWss = LOGIN_BY_IP?false:true;
        //更新频率设置100
        args.updateHZ = 100;
        KBEngine.create(args);

        // 初始化UI
        this.initUI();
        // 安装这个场景需要监听的KBE事件
        this.installEvents();

        var obj = new GUIDebugLayer();

        //开始登陆
        this.InitLogin();

    },

    /* -----------------------------------------------------------------------/
    							UI 相关
    /------------------------------------------------------------------------ */
    initUI: function () {


        // 登录按钮
        // if (this.logintButton) {
        //     let loginClickEventHandler = new cc.Component.EventHandler();
        //     loginClickEventHandler.target = this.node //这个 node 节点是你的事件处理代码组件所属的节点
        //     loginClickEventHandler.component = "StartScene";//这个是代码文件名
        //     loginClickEventHandler.handler = 'touchLoginButtonEvent';
        //     loginClickEventHandler.customEventData = "1";
        //     this.logintButton.clickEvents.push(loginClickEventHandler);
        // }


        // ask the window size
        let _size = cc.winSize;
        // 打印客户端信息
        this.clientVersion = new cc.Node('clientVersion');
        this.clientVersion.parent = cc.find("Canvas");
        this.clientVersion.anchorX = 0;
        this.clientVersion.anchorY = 1;
        this.clientVersion.setPosition(-_size.width * 0.5 + 20, _size.height * 0.5 - 20);
        this.clientVersion.color = new cc.Color(0, 255, 0, 255);

        let clientLabel = this.clientVersion.addComponent(cc.Label);
        clientLabel.fontSize = 20;
        clientLabel.string = "clientVersion: " + KBEngine.app.clientVersion;

        this.clientScriptVersion = new cc.Node('clientScriptVersion');
        this.clientScriptVersion.parent = cc.find("Canvas");
        this.clientScriptVersion.anchorX = 0;
        this.clientScriptVersion.anchorY = 1;
        this.clientScriptVersion.setPosition(-_size.width * 0.5 + 20, _size.height * 0.5 - 50);
        this.clientScriptVersion.color = new cc.Color(0, 255, 0, 255);

        let clientScriptLabel = this.clientScriptVersion.addComponent(cc.Label);
        clientScriptLabel.fontSize = 20;
        clientScriptLabel.string = "clientScriptVersion: " + KBEngine.app.clientScriptVersion;

        // 打印服务器版本信息
        this.serverVersion = new cc.Node('serverVersion');
        this.serverVersion.parent = cc.find("Canvas");
        this.serverVersion.anchorX = 0;
        this.serverVersion.anchorY = 1;
        this.serverVersion.setPosition(-_size.width * 0.5 + 20, _size.height * 0.5 - 80);
        this.serverVersion.color = new cc.Color(0, 255, 0, 255);

        this.serverVersionLabel = this.serverVersion.addComponent(cc.Label);
        this.serverVersionLabel.fontSize = 20;
        this.serverVersionLabel.string = "clientVersion: ";

        this.serverScriptVersion = new cc.Node('serverScriptVersion');
        this.serverScriptVersion.parent = cc.find("Canvas");
        this.serverScriptVersion.anchorX = 0;
        this.serverScriptVersion.anchorY = 1;
        this.serverScriptVersion.setPosition(-_size.width * 0.5 + 20, _size.height * 0.5 - 110);
        this.serverScriptVersion.color = new cc.Color(0, 255, 0, 255);

        this.serverScriptVersionLabel = this.serverScriptVersion.addComponent(cc.Label);
        this.serverScriptVersionLabel.fontSize = 20;
        this.serverScriptVersionLabel.string = "clientScriptVersion: ";

    },


    // 登录按钮
    touchLoginButtonEvent: function (sender, data) {
        console.log('login event:', sender, data);
        GUIDebugLayer.debug.INFO_MSG("Connect to server...");
        this.userName = Math.random() * 1000;
        KBEngine.INFO_MSG("login name=" + this.userName);
        KBEngine.Event.fire("login", this.userName, "123456", "kbengine_cocos2d_js_demo");

    },
    randomstring: function(L){
        var s= '';
        var randomchar=function(){
         var n= Math.floor(Math.random()*62);
         if(n<10) return n; //0-9
         if(n<36) return String.fromCharCode(n+55); //A-Z
         return String.fromCharCode(n+61); //a-z
        }
        while(s.length< L) s+= randomchar();
        return s;
    },

    InitLogin: function () {
        this.userName = this.randomstring(4);
        KBEngine.INFO_MSG("login name=" + this.userName);
        KBEngine.Event.fire("login", this.userName, "123456", "kbengine_cocos2d_js_demo");

        app.callback(11,this.userName);
    },

    /* -----------------------------------------------------------------------/
    							KBEngine 事件响应
    /------------------------------------------------------------------------ */
    installEvents: function () {
        // common
        KBEngine.Event.register("onKicked", this, "onKicked");
        KBEngine.Event.register("onDisconnected", this, "onDisconnected");
        KBEngine.Event.register("onConnectionState", this, "onConnectionState");

        // login
        KBEngine.Event.register("onCreateAccountResult", this, "onCreateAccountResult");
        KBEngine.Event.register("onLoginFailed", this, "onLoginFailed");
        KBEngine.Event.register("onVersionNotMatch", this, "onVersionNotMatch");
        KBEngine.Event.register("onScriptVersionNotMatch", this, "onScriptVersionNotMatch");
        KBEngine.Event.register("onLoginBaseappFailed", this, "onLoginBaseappFailed");
        KBEngine.Event.register("onLoginSuccessfully", this, "onLoginSuccessfully");
        KBEngine.Event.register("onReloginBaseappFailed", this, "onReloginBaseappFailed");
        KBEngine.Event.register("onReloginBaseappSuccessfully", this, "onReloginBaseappSuccessfully");
        KBEngine.Event.register("onLoginBaseapp", this, "onLoginBaseapp");
        KBEngine.Event.register("Loginapp_importClientMessages", this, "Loginapp_importClientMessages");
        KBEngine.Event.register("Baseapp_importClientMessages", this, "Baseapp_importClientMessages");
        KBEngine.Event.register("Baseapp_importClientEntityDef", this, "Baseapp_importClientEntityDef");

        // selavatars(register by scripts)
        KBEngine.Event.register("onReqAvatarList", this, "onReqAvatarList");
        KBEngine.Event.register("onCreateAvatarResult", this, "onCreateAvatarResult");
        KBEngine.Event.register("onRemoveAvatar", this, "onRemoveAvatar");

        KBEngine.Event.register("onReqAvatarTemp", this, "onReqAvatarTemp");


    },


    onRemoveAvatar: function (dbid, avatars) {
    },
    onCreateAvatarResult: function (retcode, info, avatars) {
        if (retcode == 0) {
            this.showCreatePlayerUI(false);

            GUIDebugLayer.debug.INFO_MSG("Loading(加载)...");

            // 选择这个角色进入游戏
            KBEngine.app.player().selectAvatarGame(info.dbid);

            // 切换到场景
            // cc.director.runScene(new WorldScene());	
            return;
        }
        else {
            GUIDebugLayer.debug.ERROR_MSG("Create Avatar is error(" + retcode + ")! (创建角色错误)");
        }
    },
    onKicked: function (failedcode) {
        GUIDebugLayer.debug.ERROR_MSG("kick, disconnect!, reason=" + KBEngine.app.serverErr(failedcode));
    },

    onDisconnected: function () {
        GUIDebugLayer.debug.ERROR_MSG("disconnect! will try to reconnect...");
        this.reloginCount = 0;

        this.scheduleOnce(function timerfn() {
            this.onReloginBaseappTimer(this);
        }, 1);
    },

    onReloginBaseappTimer: function (self) {
        if(KBEngine.app.socket != undefined && KBEngine.app.socket != null)
        {
        	return;
        }

        if(this.reloginCount >= 3)
        {
            // 切换起始到场景
            console.log('this.reloginCount:',this.reloginCount);
        	// cc.director.runScene(new StartScene());
        	return;
        }

        this.reloginCount += 1;

        GUIDebugLayer.debug.ERROR_MSG("will try to reconnect(" + this.reloginCount + ")...");
        KBEngine.app.reloginBaseapp();
        this.scheduleOnce(function timerfn() {
            self.onReloginBaseappTimer(self);
        }, 1);
    },

    onReloginBaseappFailed: function (failedcode) {
        GUIDebugLayer.debug.ERROR_MSG("reogin is failed(断线重连失败), err=" + KBEngine.app.serverErr(failedcode));
    },

    onReloginBaseappSuccessfully: function () {
        GUIDebugLayer.debug.INFO_MSG("reogin is successfully!(断线重连成功!)");
    },

    onConnectionState: function (success) {
        if (!success)
            GUIDebugLayer.debug.ERROR_MSG("Connect(" + KBEngine.app.ip + ":" + KBEngine.app.port + ") is error! (连接错误)");
        else
            GUIDebugLayer.debug.INFO_MSG("Connect successfully, please wait...(连接成功，请等候...)");
    },


    onCreateAccountResult: function (retcode, datas) {
        if (retcode != 0) {
            GUIDebugLayer.debug.ERROR_MSG("CreateAccount is error(注册账号错误)! err=" + retcode);
            return;
        }

        //if(KBEngineApp.validEmail(stringAccount))
        //{
        //	GUIDebugLayer.debug.INFO_MSG("createAccount is successfully, Please activate your Email!(注册账号成功，请激活Email!)");
        //}
        //else
        {
            GUIDebugLayer.debug.INFO_MSG("CreateAccount is successfully!(注册账号成功!)");
        }
    },

    onLoginFailed: function (failedcode, serverdatas) {
        if (failedcode == 20) {
            GUIDebugLayer.debug.ERROR_MSG("Login is failed(登陆失败), err=" + KBEngine.app.serverErr(failedcode) + ", " + serverdatas);
        }
        else {
            GUIDebugLayer.debug.ERROR_MSG("Login is failed(登陆失败), err=" + KBEngine.app.serverErr(failedcode));
        }
    },

    onVersionNotMatch: function (clientVersion, serverVersion) {
        GUIDebugLayer.debug.ERROR_MSG("Version not match(curr=" + clientVersion + ", srv=" + serverVersion + " )(版本不匹配)");
        KBEngine.ERROR_MSG("Execute the gensdk script to generate matching client SDK in the server-assets directory.");
        this.serverScriptVersionLabel.string = "serverScriptVersion: " + KBEngine.app.serverScriptVersion;
        this.serverVersionLabel.string = "serverVersion: " + KBEngine.app.serverVersion;
    },

    onScriptVersionNotMatch: function (clientScriptVersion, serverScriptVersion) {
        GUIDebugLayer.debug.ERROR_MSG("ScriptVersion not match(curr=" + clientScriptVersion + ", srv=" + serverScriptVersion + " )(脚本版本不匹配)");
        // this.serverScriptVersion.setString("serverScriptVersion: " + KBEngine.app.serverScriptVersion);
        // this.serverVersion.setString("serverVersion: " + KBEngine.app.serverVersion);	    	
    },

    onLoginBaseappFailed: function (failedcode) {
        GUIDebugLayer.debug.ERROR_MSG("LoginBaseapp is failed(登陆网关失败), err=" + KBEngine.app.serverErr(failedcode));
    },

    onLoginSuccessfully: function (rndUUID, eid, accountEntity) {
        GUIDebugLayer.debug.INFO_MSG("Login is successfully!(登陆成功!)");

        this.serverScriptVersionLabel.string = "serverScriptVersion: " + KBEngine.app.serverScriptVersion;
        this.serverVersionLabel.string = "serverVersion: " + KBEngine.app.serverVersion;
    },

    onLoginBaseapp: function () {
        GUIDebugLayer.debug.INFO_MSG("Connect to loginBaseapp, please wait...(连接到网关， 请稍后...)");
    },

    Loginapp_importClientMessages: function () {
        GUIDebugLayer.debug.INFO_MSG("Loginapp_importClientMessages ...");
    },

    Baseapp_importClientMessages: function () {
        GUIDebugLayer.debug.INFO_MSG("Baseapp_importClientMessages ...");
    },

    Baseapp_importClientEntityDef: function () {
        GUIDebugLayer.debug.INFO_MSG("Baseapp_importClientEntityDef ...");

        this.serverScriptVersionLabel.string = "serverScriptVersion: " + KBEngine.app.serverScriptVersion;
        this.serverVersionLabel.string = "serverVersion: " + KBEngine.app.serverVersion;
    },

    onReqAvatarTemp: function () {
        // 切换到场景
        cc.director.loadScene("matching", () => {
            console.log('进入匹配场景');
        });
    },
    // 获取到人物列表再跳转
    onReqAvatarList: function (avatars) {

        //如果没有角色那么请求创建一个角色
        if (KBEngine.app.player().avatars.values.length <= 0) {
            GUIDebugLayer.debug.INFO_MSG("Create avatar(创建角色)...");
            KBEngine.app.player().reqCreateAvatar(1, "123");
            return;
        }
        // 选择这个角色进入游戏
        //   KBEngine.app.player().selectAvatarGame(KBEngine.app.player().avatars.values[0].dbid);

        GUIDebugLayer.debug.INFO_MSG("Loading(加载中)...");
        // 切换到场景
        cc.director.loadScene("worldScene", () => {
            console.log('进入游戏场景');
            KBEngine.INFO_MSG("load world scene finished");
        });
    },



});

