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

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

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

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

    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 > __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);
            this._currentBoxIndex++;
            await box.createFirstBg();
            this.dispatchEvent(new egret.Event(egret.Event.COMPLETE));
            resolve();
        })
    }

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

    get boxs() { return this._boxs }
}