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

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

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

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

    private BOX_CREATE_INTERVAL = 60 * 1.2;
    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.speed = this._boxSpeed;
        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;
        this.removeBoxFromList(currentBox);
    }

    removeBoxFromList(currentBox: 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.speed = this._boxSpeed;
            box.addEventListener('onDisappear', this.onDisappear, this);
            this._boxs.push(box);
            this._parent.addChild(box);
            await box.createBg();
            this._currentBoxIndex++;
            resolve();
        })
    }

    updateSpeed(val: number) {
        this._boxSpeed = val;
        this._boxs.forEach((box) => {
            box.speed = this._boxSpeed;
        });
    }

    get boxs() { return this._boxs }
}