// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import Game from "./Game";
import pg from "./pg";

const { ccclass, property } = cc._decorator;

@ccclass
export default class NewClass extends cc.Component {

    @property(cc.Node)
    layout_up: cc.Node = null;

    @property(cc.Node)
    layout_down: cc.Node = null;

    @property(cc.Node)
    item: cc.Node = null;

    onLoad() {
        pg.event.on("game_start_loop", () => { this.startLoop() })
        pg.event.on("game_stop_loop", () => { this.stopLoop() })
    }
    protected onDestroy(): void {
        pg.event.off("game_start_loop");
        pg.event.off("game_stop_loop");
        this.unschedule(this.createItem);
    }
    startLoop() {
        //播放一次题干后继续
        this.lastId = [];
        this.unschedule(this.createItem);
        this.schedule(this.createItem, 1);
    }
    pauseLoop() {
    }
    stopLoop() {
        this.unschedule(this.createItem);
    }
    private lastId: Array<number>;
    createItem() {
        if (Game.getIns().pause || Game.getIns().isOver) return;
        console.log("createItem");
        let posList = [
            cc.v2(-640, -13),
            cc.v2(-220, -13),
            cc.v2(220, -13),
            cc.v2(640, -13),
            cc.v2(-640, -280),
            cc.v2(-220, -280),
            cc.v2(220, -280),
            cc.v2(640, -280)
        ];
        let id = Math.floor(Math.random() * posList.length);
        while (this.lastId.some(i => i == id)) {
            id = Math.floor(Math.random() * posList.length);
        }
        this.lastId.push(id);
        if (this.lastId.length == 4) {
            this.lastId.shift();
        }
        let layout = id <= 3 ? this.layout_up : this.layout_down;
        let pos = posList[id];
        let item = pg.view.clone(this.item);
        item.x = pos.x;
        item.y = pos.y;
        layout.addChild(item);
        let data = Game.getIns().penguin;
        //设置item内部内容。
        item.getComponent("item").showAni(data);
    }
}
