// Learn TypeScript:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/typescript.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html

const { ccclass, property } = cc._decorator;

@ccclass
export default class Test extends cc.Component {

    @property(cc.Prefab)
    monsterPrefab: cc.Prefab = null;

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

    nodePool: cc.NodePool = null;

    _time = 0;
    start() {
        this.nodePool = new cc.NodePool();
    }

    putToNodePool(monster) {
        this.nodePool.put(monster);
    }

    getFromNodePool() {
        return this.nodePool.get();
    }

    createMonster() {
        let monster = this.getFromNodePool();
        if (!monster) {
            monster = cc.instantiate(this.monsterPrefab);
            //monster = cc.instantiate(this.img);
        }

        monster.x = 400;
        monster.y = 10

        this.node.addChild(monster);
        monster.runAction(cc.sequence(cc.moveBy(8, 0, 400), cc.callFunc(this.die.bind(this))));
    }

    die(target: cc.Node) {
        this.putToNodePool(target);
    }

    update(dt) {
        //5秒钟出一个怪
        this._time += dt;
        if (this._time > 5) {
            this._time = 0;
            this.createMonster();
        }
    }

}
