var gameConfig = require("./GameConfig.js");
var lib = require("../Library");
var globalConfig = require("../Global");

cc.Class({
    extends: cc.Component,

    properties: {
        gameStates: {
            default: null,
            type: cc.Node,
            serializable: true,
        },
        ui: {
            default: null,
            type: cc.Node,
            serializable: true,
        },
        player1: {
            default: null,
            type: cc.Node,
            serializable: true,
        },
        player2: {
            default: null,
            type: cc.Node,
            serializable: true,
        },
        canvas: {
            default: null,
            type: cc.Node,
            serializable: true,
        },
        readyGoAnim: {
            default: null,
            type: cc.Node,
            serializable: true,
        },
        handrailPrefab: {
            default: null,
            type: cc.Prefab,
        },
        starting: {
            default: null,
            type: cc.Node,
            serializable: true,
        },
        terminal: {
            default: null,
            type: cc.Node,
            serializable: true,
        },
        bgm: {
            default: null,
            type: cc.AudioSource,
            serializable: true,
        },
        Player1Arrow: {
            default: null,
            type: cc.Node,
            serializable: true,
        },
        startAudio: {
            default: null,
            type: cc.AudioClip,
        },
    },
    // LIFE-CYCLE CALLBACKS:
    onLoad() {
        this.init();
        this.initUI();

        //添加动画事件监听
        this.armatureDisplay.addEventListener(dragonBones.EventObject.COMPLETE, this.animationEventHandler, this);
    },
    init() {
        //playerControllerScript
        this.pConSt1 = this.player1.getComponent('BasePlayerController');
        this.pConSt2 = this.player2.getComponent('BasePlayerController');
        // because player controller onload event after game mode so use getChildByName to get PlayerStates
        this.pStatesSt1 = this.pConSt1.node.getChildByName('PlayerStates').getComponent('BasePlayerStates');
        this.pStatesSt2 = this.pConSt2.node.getChildByName('PlayerStates').getComponent('BasePlayerStates');

        this.ctorSt1 = this.pConSt1.node.getChildByName('Charactor').getComponent('BaseCharactor');
        this.ctorSt2 = this.pConSt2.node.getChildByName('Charactor').getComponent('BaseCharactor');
     
        //gameStatesScript
        this.gStatesSt = this.gameStates.getComponent('GameStates');
        this.armatureDisplay = this.readyGoAnim.getComponent(dragonBones.ArmatureDisplay);
        this.armature = this.armatureDisplay.armature();
    },
    initUI() {
        this.ui.zIndex = 10003;
        // init player information
        let playerUI1 = this.ui.getChildByName('Player1');
        let pUIName1 = playerUI1.getChildByName('NameBG').getChildByName('Name');
        let pUIAvatar1 = playerUI1.getChildByName('Mask').getChildByName('Avatar');
        let pUIGender1 = playerUI1.getChildByName('Gender');

        let playerUI2 = this.ui.getChildByName('Player2');
        let pUIName2 = playerUI2.getChildByName('NameBG').getChildByName('Name');
        let pUIAvatar2 = playerUI2.getChildByName('Mask').getChildByName('Avatar');
        let pUIGender2 = playerUI2.getChildByName('Gender');

        let setGender = function (genderNode, bMale) {
            if (bMale) {
                genderNode.getChildByName('Female').active = false;
                genderNode.getChildByName('Male').active = true;
            } else {
                genderNode.getChildByName('Female').active = true;
                genderNode.getChildByName('Male').active = false;
            }
        };

        pUIName1.getComponent(cc.Label).string = globalConfig.Name;
        pUIName2.getComponent(cc.Label).string = globalConfig.rivalName;

        lib.setImageBase64(globalConfig.avatarBase64, function (texture2D) {
            pUIAvatar1.getComponent(cc.Sprite).spriteFrame = new cc.SpriteFrame(texture2D);
        });

        lib.setImageBase64(globalConfig.rivalAvatarBase64, function (texture2D) {
            pUIAvatar2.getComponent(cc.Sprite).spriteFrame = new cc.SpriteFrame(texture2D);
        });

        setGender(pUIGender1, globalConfig.gender);
        setGender(pUIGender2, globalConfig.rivalGender);
    },
    start()
    {
        //because player state have not be created so this code write start function
        //currentStartPositionX from start line(720,0) not (0,0)
        //跨栏总数是两个部分组  和同样间隔的跨栏组 和当组里面创建出来多少跨栏
        let cStartPX = 720;
        let hPSetArr = gameConfig.handrailPosSetArr;
   
        for(let i = 0;i<hPSetArr.length;i++)
        {
            let space = hPSetArr[i].handrailSpace;
            for(let j = 0;j<hPSetArr[i].handrailNum;j++)
            {
                cStartPX+=space;
                this.pStatesSt1.handrailArr.push({"startPX":(cStartPX),
                    'bFallDown':0});
                this.pStatesSt2.handrailArr.push({"startPX":(cStartPX),
                    'bFallDown':0});
            }
        }

        this.terminal.x = cStartPX + 720*2;
    },
    animationEventHandler(event)
    {
        if (event.type === dragonBones.EventObject.COMPLETE)
        {
            if (event.animationState.name === "animation")
            {
                // Debug.Log("attack 动作播放完毕！！！");
                this.startGame();
                this.bgm.getComponent(cc.AudioSource).play();
            }
        }
    },
    startGame()
    {
        cc.audioEngine.playEffect(this.startAudio, 0, function () {});
        this.resetZindex();
        this.playerRun();
        
        //如果总共要创建0个跨栏就不创建，如果1个就创建一个，如果2个以上就创建两个
        //之所以创建两个是因为不换穿帮，1个可以看到前面的跨栏突然生产
        if(this.pStatesSt1.handrailArr.length == 1)
        {
            this.createHandrail();
        }
        else if(this.pStatesSt1.handrailArr.length > 1)
        {
            for(let i = 0;i<2;i++)
            {
                this.createHandrail();    
            }
        }
      
        this.pStatesSt1.nextHandrail = this.gStatesSt.drawedhandrailArr[0].handrail;

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

        //destroy Arrow on the player top
        this.schedule(function() {
            this.Player1Arrow.destroy();
        }, 5, 0, 0);
    },
    countGameTime()
    {
        this.gStatesSt.gameTime++;
    },
    createHandrail()
    {
        if (this.gStatesSt.currentHandrailIndex == this.pStatesSt1.handrailArr.length && 
            this.gStatesSt.currentHandrailIndex !=0) 
            {
                return -1;
            }
        //get new handrail position x
        let currentLevel = gameConfig.handrailPosSetArr[this.gStatesSt.currentHandrailPositionLevel];
        let positionSpace = currentLevel.handrailSpace;
        let handrailPos = this.gStatesSt.lastHandrailPosition + positionSpace;
        this.gStatesSt.lastHandrailPosition = handrailPos;
        //create handrail
        let res = this.handrailPrefab;

        let handrail = cc.instantiate(res);
        handrail.x = handrailPos + this.gStatesSt.startLinePX;
        handrail.zIndex = 1;
        this.canvas.addChild(handrail);
        this.gStatesSt.drawedhandrailArr.push({'handrail':handrail,
            index:this.gStatesSt.currentHandrailIndex});
      
        //set player2 have not drawed hurndrail state
        let handrail2 = handrail.getChildByName('Kuolan2');
        if(this.pStatesSt2.handrailArr[this.gStatesSt.currentHandrailIndex].bFallDown)
        {
            let spine = handrail2.getComponent(sp.Skeleton);
            spine.setAnimation(0, 'Idl1_3', false);
        }

        //count current handrailNum and
        this.gStatesSt.currentHandrailIndex++;
        this.gStatesSt.currentHandrailIndexInLevel++;

        if (this.gStatesSt.currentHandrailIndexInLevel == currentLevel.handrailNum)
        {
            this.gStatesSt.currentHandrailIndexInLevel = 0;
            this.gStatesSt.currentHandrailPositionLevel++;
        }

        return handrail.x;
    },
    resetZindex() {
        this.pConSt1.resetZindex();
        this.pConSt2.resetZindex();
    },
    playerRun() {
        this.pConSt1.currentState = this.pStatesSt1.playerAnimState.run;
        this.ctorSt1.run('idle');

        this.pConSt2.currentState = this.pStatesSt2.playerAnimState.run;
        this.ctorSt2.run('idle');
    },
    replay()
    {
        this.schedule(function() {
            cc.director.loadScene("Game");
        }, 0.1, 0, 0);
    }
});
