import Box from "./Box";
import { getBoxKeyList } from "./data/getBoxKeyList";

export default class BoxListCtrl {
    private _parent: egret.Sprite;
    private _boxKeys: string[];
    private _boxs: Box[];

    constructor(parent: egret.Sprite) {
        this._parent = parent;
        this._boxs = [];
        this.init();
    }

    init() {
        this._boxKeys = getBoxKeyList();
    }

    private BOX_CREATE_INTERVAL = 60 * 4;
    private _timer: number;
    private _currentBoxIndex = 0;
    private _frameCounter = 0;
    /** 创建其他的boxs */
    resume() {
        this._parent.addEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame, this);
        this._boxs.forEach(box => box.resume());
    }

    pause() {
        this._parent.removeEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame, this);
        this._boxs.forEach(box => box.pause());
    }

    onEnterFrame() {
        this._frameCounter++;
        if (this._frameCounter > this.BOX_CREATE_INTERVAL) {
            this._frameCounter = 0;
            this.createBox();
            this._currentBoxIndex++;
            if (this._currentBoxIndex >= this._boxKeys.length)
                this._currentBoxIndex = 0;
        }
    }

    createBox() {
        const box = new Box(this._boxKeys[this._currentBoxIndex]);
        box.addEventListener('onDisappear', this.onDisappear, this);
        this._parent.addChild(box);
        box.createBg();
        this._boxs.push(box);
    }

    onDisappear(e: egret.Event) {
        const currentBox = e.target as Box;
        const index = this._boxs.indexOf(currentBox);
        if (index != -1)
            this._boxs.splice(index, 1);
    }

    reset() {
        clearInterval(this._timer);
        this._timer = 0;
        this._currentBoxIndex = 0;
    }

    createFirstBox() {
        return new Promise(async (resolve) => {
            const box = new Box(this._boxKeys[this._currentBoxIndex]);
            box.addEventListener('onDisappear', this.onDisappear, this);
            this._boxs.push(box);
            this._parent.addChild(box);
            await box.createBg();
            this._currentBoxIndex++;
            resolve();
        })
    }

    get boxs() { return this._boxs }
}