import SheetAnimation from "../components/SheetAnimation";
export default class Box extends egret.Sprite {
    private _pic: SheetAnimation;
    private _type: string;
    private START_SCALE = 0.5;
    private START_X = 395;
    private START_Y = 350;
    private END_Y = 1100;
    private MIDDLE_Y = 700;
    constructor(type) {
        super();
        this._type = type;
        this._pic = new SheetAnimation();
        this.addChild(this._pic);
    }

    onEnterFrame() {
        this.y += __boxMoveSpeed__;
        let distance = this.y - this.START_Y;
        const totalDistance = (this.MIDDLE_Y - this.START_Y);
        if (distance > totalDistance)
            distance = totalDistance;
        const scale = this.START_SCALE + (1 - this.START_SCALE) * (distance / totalDistance);
        this.scaleX = this.scaleY = scale;
        if (this.y > this.END_Y && !this._onDisappear) {
            this.disappear();
        }
    }

    move() {
        this._pic.play();
        this.addEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame, this);
    }

    private _onDisappear: boolean;
    disappear() {
        this._onDisappear = true;
        this._pic.destroy();
        egret.Tween.get(this).to({ alpha: 0 }, 500).call(this.destroy, this);
    }

    destroy() {
        this.removeEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame, this);
        this.parent.removeChild(this);
    }

    stopMove() {

    }

    async createBg() {
        let url = this.boxData.skin;
        return new Promise((resolve) => {
            RES.getResByUrl(url, (sheet: egret.SpriteSheet) => {
                this._pic.sheet = sheet;
                this._pic.fps = 10;
                egret.Tween.get(this)
                    .set({ alpha: 0, scaleX: 0, scaleY: 0, x: this.START_X, y: this.START_Y })
                    .to({ alpha: 1, scaleX: this.START_SCALE, scaleY: this.START_SCALE }, 1500, egret.Ease.getBackInOut(2))
                    .call(this.move, this);
                this.anchorOffsetX = this.boxData.offset[0];
                this.anchorOffsetY = this.boxData.offset[1];
                resolve(this);
            }, this, RES.ResourceItem.TYPE_SHEET);
        });
    }

    get type() { return this._type }
    get boxData() { return __boxmap__[this._type] }
}