var webView = require("../WebView");
cc.Class({
    extends: cc.Component,

    properties: {
        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() {
        this.init();

        //init web sdk
        if (this.openInWebview())
        {
            // 在app内Webview打开
            webView.init(this.node);
        }
        else
        {
            this.initPlayer1();
        }

        //register event from webView 监听web服务器的回调
        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);
    },
    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');
    },
    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.openInWebview())
            {
                webView.getAiInfo();
            }
            else
            {
                this.resetRivalUIByData(webView.rivalUserName, webView.rivalGender, webView.rivalavatarBase64);
            }
        }
    },
    //设置性别
    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;
        }.bind(this));
    },
    //加载头像
    loadAvatar(avatarBase64,callback)
    {
        this.setImageBase64(avatarBase64,function (texture2D) {
            let frame = new cc.SpriteFrame(texture2D);
            callback && callback(frame);
        });
    },
    //刷新计时器
    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;
            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;
    },
    //tool funtion
    //判断是在一般浏览器还是在webview里面运行
    openInWebview () {
        let ua = navigator.userAgent.toLowerCase()
        if (ua.match(/MicroMessenger/i) == 'micromessenger') { // 微信浏览器判断
            return false
        } else if (ua.match(/QQ/i) == 'qq') { // QQ浏览器判断
            return false
        } else if (ua.match(/WeiBo/i) == "weibo") {
            return false
        } else {
            if (ua.match(/Android/i) != null) {
                return ua.match(/browser/i) == null
            } else if (ua.match(/iPhone/i) != null) {
                return ua.match(/safari/i) == null
            } else {
                return (ua.match(/macintosh/i) == null && ua.match(/windows/i) == null)
            }
        }
    },
    //base64转texture
    setImageBase64(base64,callback){
        let img = new Image();
        img.src = base64;
        img.onload = function(){
            let texture = new cc.Texture2D();
            texture.initWithElement(img);
            texture.handleLoadedTexture();
            if (callback)
                callback(texture);
        }
    },
    //call back
    onGameInit(data) {
        this.initPlayer1();
    },
    onAiRandomInfo(data) {
        this.resetRivalUIByData(webView.rivalUserName, webView.rivalGender, webView.rivalavatarBase64);
    },
    onUrlToBase64(data)
    {
        webView.rivalavatarBase64 = data.base64;
        this.resetRivalUIByData(webView.rivalUserName,  webView.rivalGender, webView.rivalavatarBase64);
    }
});
