var webView = require("../WebView");
var lib = require("../Library");
var lockStepClient = require("../LockStepClient");
var globalConfig = require("../Global");

cc.Class({
    extends: cc.Component,

    properties: {
        nextSceneName: {
            default: '',
        },

        player1: {
            default: null,
            type: cc.Node,
        },
        player2: {
            default: null,
            type: cc.Node,
        },
        titleTxt: {
            default: null,
            type: cc.Node,
        },
        timeTxt: {
            default: null,
            type: cc.Node,
        },
        waitTxt: {
            default: null,
            type: cc.Node,
        },
        successAudio: {
            default: null,
            type: cc.AudioClip,
        },
        meteorLine: {
            default: null,
            type: cc.Node,
        },
    },
    onLoad() {
        this.init();
        //从服务器下载获取当前玩家信息 get player info from webserver

        if (lib.openInWebview()) {
            this.getPlayerInfoFromWebServer();
        }
        //count down time to match ui  开启计时，时间到没有匹配到玩家就生成Ai开始游戏
        let interval = 1; // 以秒为单位的时间间隔let
        let repeat = cc.macro.REPEAT_FOREVER; // 重复次数
        let delay = 0; // 开始延时
        this.schedule(this.countTime, interval, repeat, delay);

        //开始匹配
        this.startMatching();

        // 预加载下一个游戏场景
        // because loading scene not a immediately stuff,A smart phone will cost 5-8 second for loading
        if(this.nextSceneName!='')
        {
            cc.director.preloadScene(this.nextSceneName, function () {
                cc.log("Next scene preloaded");
            });
        }
    },
    init() {
        this.matchTime = 0;

        this.name1 = this.player1.getChildByName('Name');
        this.name2 = this.player2.getChildByName('Name');

        this.gender1 = this.player1.getChildByName('Gender');
        this.gender2 = this.player2.getChildByName('Gender');

        this.avatarSp1 = this.player1.getChildByName('Mask').getChildByName('AvatarSp');
        this.avatarSp2 = this.player2.getChildByName('Mask').getChildByName('AvatarSp');

    },
    getPlayerInfoFromWebServer(){
        //init web sdk
        if (lib.openInWebview())
        {
            // 在app内Webview打开
            webView.register(this.node);
            this.node.on('onGameInit',this.onGameInit,this);
            this.node.on('onAiRandomInfo',this.onAiRandomInfo,this);
            this.node.on('onUrlToBase64',this.onUrlToBase64,this);
        }
    },
    countTime() {
        //update countdown time on UI
        this.timeTxt.getComponent(cc.Label).string = this.updateTime(this.matchTime);
        this.matchTime++;

        if (this.matchTime > 10)
        {
            this.unschedule(this.countTime);
            this.generateAI();
        }
    },
    updateTime(t) {
        let theTime = Math.floor(t);
        let theTime1 = 0;// 分

        if (theTime > 60)
        {
            theTime1 = parseInt(theTime / 60);
            theTime = parseInt(theTime % 60);
        }
        let result = (theTime1 < 10 ? "0" + theTime1 : theTime1) + ":" + (theTime < 10 ? "0" + theTime : theTime);
        return result;
    },
    startMatching() {

        let Self = this;
        globalConfig.openid = new Date().getMilliseconds().toString();
     
        lockStepClient.login(globalConfig.openid,this.name,this.avatarUrl,this.gender,function(e){
            lockStepClient.match(globalConfig.openid,function (other_openid,other_name,other_avatarUrl,other_gender) {

                Self.matched(other_avatarUrl,other_name,other_gender,false);
            });
        });
    },
    matched(other_avatarUrl,other_name,other_gender,bAi) {
        //停止计时 stop counting down time
        this.unschedule(this.countTime);

        // cancel ai
        globalConfig.bAi = bAi;
        //保存对手的信息 save rival info
        globalConfig.rivalAvatarUrl = other_avatarUrl;
        globalConfig.rivalName = other_name;
        globalConfig.rivalGender = other_gender;

        //change top UI
        this.meteorLine.active = true;
        this.titleTxt.getComponent(cc.Label).string = "匹配成功";
        this.timeTxt.active = false;
        this.waitTxt.active = false;
        //show rival information
        this.player2.getChildByName("DotAnimation").active = false;
        this.player2.active = true;
        this.name2.active = true;
        this.gender2.active = true;
        this.avatarSp2.active = true;

        //渠道下一个场景 go to next scene
        if(this.nextSceneName!='')
        {
            cc.director.loadScene(this.nextSceneName);
        }
    },
    setGender(gender, bBoy) {
        this.iconBoy = gender.getChildByName('IconBoy');
        this.iconGirl = gender.getChildByName('IconGirl');
        if (!bBoy) {
            this.iconBoy.active = true;
            this.iconGirl.active = false;
        } else {
            this.iconBoy.active = false;
            this.iconGirl.active = true;
        }
    },

    loadAvatar(avatarBase64,callback)
    {
        lib.setImageBase64(avatarBase64,function (texture2D) {
            let frame = new cc.SpriteFrame(texture2D);
            callback && callback(frame);
        });
    },
    resetRivalUIByData(userName, gender, avatarBase64) {
        this.name2.getComponent(cc.Label).string = userName;
        this.setGender(this.gender2, gender);
        // loading avatar

        //for mobile device we need to download avatar whatever AI or others
        this.loadAvatar(avatarBase64, function (frame) {
            this.avatarSp2.getComponent(cc.Sprite).spriteFrame = frame;
            cc.audioEngine.playEffect(this.successAudio, false);
            this.scheduleOnce(() => {
                this.matched(globalConfig.rivalAvatarUrl,globalConfig.rivalName,globalConfig.rivalGender,true);
            }, 2);
        }.bind(this));
    },
    generateAI() {
        if (lib.openInWebview())// 在app内Webview打开
        {
            // match failed so we need to get a Ai information to start game
            webView.getAiInfo();
        } else {
            //TODO
            //In browser we just use default information to generate AI
            this.resetRivalUIByData(globalConfig.name, globalConfig.gender, globalConfig.avatarBase64);
        }
    },
    onUrlToBase64(data)
    {
        globalConfig.rivalavatarBase64 = data.base64;
        this.resetRivalUIByData(globalConfig.rivalName,  globalConfig.rivalGender, globalConfig.rivalAvatarBase64);
    },
    onGameInit(data) {
        globalConfig.name = data.userName;
        globalConfig.avatarUrl = data.avatarUrl;
        globalConfig.avatarBase64 = data.avatarBase64Url;
        globalConfig.gender = data.gender;
        globalConfig.calorieParams = data.calorieParams;
        globalConfig.device = data.device;
        this.initPlayerUI(globalConfig.name, globalConfig.gender,globalConfig.avatarBase64);
    },
    initPlayerUI(name,gender,avatarBase64) {
        this.name1.getComponent(cc.Label).string = name;
        this.setGender(this.gender1, gender);
        this.loadAvatar(avatarBase64,function (frame) {
            this.avatarSp1.getComponent(cc.Sprite).spriteFrame = frame;
        }.bind(this));
    },
    onAiRandomInfo(data) {
        globalConfig.rivalAvatarBase64 = data.aiAvatarBase64Url;
        globalConfig.rivalName = data.aiName;
        globalConfig.rivalGender = data.aiGender;
        this.resetRivalUIByData(globalConfig.rivalName, globalConfig.rivalGender, globalConfig.rivalAvatarBase64);
    },
});
