let webView = require("../WebView");
let lib = require("../Library");
let mgobe = require("../Mgobe");
cc.Class({
    extends: cc.Component,

    properties: {
        nextSceneName: {
            default: '',
        },
        bOpenMgobeServer: {
            default: false,
        },
        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() {
        let self = this;
        this.init();

        //init web sdk
        if (lib.openInWebview())
        {
            // 在app内Webview打开
            webView.init(this.node,function () {
                self.starMatching();
            });
        }

        //register event from webView
        this.node.on('onGameInit',this.onGameInit,this);
        this.node.on('onAiRandomInfo',this.onAiRandomInfo,this);
        this.node.on('onUrlToBase64',this.onUrlToBase64,this);

        //count down time to match ui
        let interval = 1;  // 以秒为单位的时间间隔let
        let repeat = cc.macro.REPEAT_FOREVER;  // 重复次数
        let delay = 0;  // 开始延时
        this.schedule(this.countTime, interval, repeat, delay);

        // 因为在手机端加载场景要5-8秒钟 所以提早加载
        // 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);
        }
    },
    init() {
        this.matchTime = 0;

        webView.avatarSpriteFrame = this.player1.getChildByName('Mask').getChildByName('AvatarSp').getComponent(cc.Sprite).spriteFrame;
        webView.rivalAvatarSpriteFrame = this.player2.getChildByName('Mask').getChildByName('AvatarSp').getComponent(cc.Sprite).spriteFrame;

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

        webView.userName = this.name1.getComponent(cc.Label).string;
        webView.rivalUserName = this.name2.getComponent(cc.Label).string;

        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');
    },
    countTime() {
        //update countdown time on UI
        this.timeTxt.getComponent(cc.Label).string = this.updateTime(this.matchTime);
        this.matchTime++;

        if (this.matchTime > 5)
        {
            this.unschedule(this.countTime);

            if(this.bOpenMgobeServer)//if using Mgobe
            {
                // 在app内Webview打开
                if(lib.openInWebview())
                {
                    mgobe.cancelPlayerMatch(function () {
                        this.generateAI();
                    }.bind(this));
                }
                else {
                    this.quickStart();
                }
            }
            else
            {
                this.quickStart();
            }
        }
    },
    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;
        }
    },
    initPlayer1() {
        this.name1.getComponent(cc.Label).string = webView.userName;
        this.setGender(this.gender1, webView.gender);
        this.loadAvatar(webView.avatarBase64,function (frame) {
            this.avatarSp1.getComponent(cc.Sprite).spriteFrame = frame;
            webView.avatarSpriteFrame = frame;
        }.bind(this));
    },
    loadAvatar(avatarBase64,callback)
    {
        lib.setImageBase64(avatarBase64,function (texture2D) {
            let frame = new cc.SpriteFrame(texture2D);
            callback && callback(frame);
        });
    },
    starMatching() {
        if(!this.bOpenMgobeServer) return;
        //before matching we need to load a cert file in resource folder
        return cc.loader.loadRes("/cacert", cc.Asset, (err, asset) => {
            console.log("加载证书结束 " + (!err));
            if (err)return;

            mgobe.cacertNativeUrl = asset.nativeUrl;

            mgobe.initSDK(function ()
            {
                // bind the init success event
                mgobe.room.onRecvFromClient = this.onRecvFromClient.bind(this);

                mgobe.matchPlayers(function ()
                {
                    //send my information to others so that they can generate rival
                    mgobe.sendMessage(JSON.stringify({
                        'avatarUrl': webView.avatarUrl,
                        'userName': webView.userName,
                        'gender': webView.gender
                    }));
                }.bind(this,lib));
            }.bind(this));
        });
    },
    updateTime(t) {
        let theTime = Math.floor(t);
        let theTime1 = 0;// 分

        if (theTime > 60)
        {
            theTime1 = parseInt(theTime / 60);
            theTime = parseInt(theTime % 60);
        }
        let result = '';

        result = (theTime1 < 10 ? "0" + theTime1 : theTime1) + ":" + (theTime < 10 ? "0" + theTime : theTime);
        return result;
    },
    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;
            webView.rivalavatarBase64 = frame;
            cc.audioEngine.playEffect(this.successAudio, false);
            this.scheduleOnce(() => {
                this.matched();
            }, 2);
        }.bind(this));
    },
    matched() {
        //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;

        this.scheduleOnce(() => {
            if(this.nextSceneName!='')
            {
                cc.director.loadScene(this.nextSceneName);
            }
        }, 1);
    },
    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(webView.userName, webView.gender, webView.avatarBase64);
        }
    },
    quickStart()
    {
        cc.audioEngine.playEffect(this.successAudio, false);
        this.scheduleOnce(() => {
            this.matched();
        }, 2);
    },
    onRecvFromClient(event) {
        console.log("收到新消息" + event.data.msg);
        this.unschedule(this.countTime);
        let data = JSON.parse(event.data.msg);

        webView.rivalavatarUrl = data.avatarUrl;
        webView.rivalUserName=data.userName;
        webView.rivalGender = data.gender;
        webView.getBase64(webView.rivalavatarUrl);
    },
    onUrlToBase64(data)
    {
        webView.rivalavatarBase64 = data.base64;
        this.resetRivalUIByData(webView.rivalUserName,  webView.rivalGender, webView.rivalavatarBase64);
    },
    onGameInit(data) {
        this.initPlayer1();
    },
    onAiRandomInfo(data) {
        this.resetRivalUIByData(webView.rivalUserName, webView.rivalGender, webView.rivalavatarBase64);
    },
});
