class MButton extends eui.Button implements eui.UIComponent {
    public downScale = 0.9;
    public scaleDuration = 50;
    public image: eui.Image;
    public labelDisplay: eui.Label;

    private touchID: number = null;
    private inited = false;
    private isWaiting = false;

    private init() {
        let offsetX = this.width / 2 - this.anchorOffsetX;
        let offsetY = this.height / 2 - this.anchorOffsetY;
        this.anchorOffsetX = this.width / 2;
        this.anchorOffsetY = this.height / 2;
        this.x += offsetX;
        this.y += offsetY;
        this.inited = true;
    }

    constructor() {
        super();
        this.addEventListener(egret.TouchEvent.TOUCH_BEGIN, (e: egret.TouchEvent) => {
            if (!this.enabled) return;
            egret.Tween.removeTweens(this);
            egret.Tween.get(this).to({ scaleX: this.downScale, scaleY: this.downScale }, this.scaleDuration);

            if (!this.inited) this.init();

            this.touchID = e.touchPointID;
            egret.MainContext.instance.stage.addEventListener(egret.TouchEvent.TOUCH_END, this.onTouchEnd, this);
        }, this);
    }

    onOnceTap(target: any, callback: (resume: () => void) => void) {
        super.onTap(target, () => {
            if (this.isWaiting) return;

            this.isWaiting = true;
            callback(() => {
                if (this && this.isWaiting) {
                    this.isWaiting = false;
                }
            });
        });
    }

    onTouchEnd(e: egret.TouchEvent) {
        if (!this.enabled) return;
        if (this.touchID == null) return;

        if (e.touchPointID == this.touchID) {
            egret.Tween.removeTweens(this);
            egret.Tween.get(this).to({ scaleX: 1, scaleY: 1 }, this.scaleDuration);
            this.touchID = null;
            egret.MainContext.instance.stage.removeEventListener(egret.TouchEvent.TOUCH_END, this.onTouchEnd, this);
        }
    }
}

export default MButton;