export default class Monkey extends egret.Sprite {
    private h = 525;
    private w = 265;
    private h0 = 8;
    private w0 = 118;
    private h1 = 23;
    private w1 = 29;
    private r1;
    private len;
    private targetY = 70;
    private targetX = 369;
     static RANGE = 60;
    private _shakeSpeed = .5;
    constructor() {
        super();
        this.anchorOffsetX = 113;
        this.anchorOffsetY = 8;
        const a = this.w0 - this.w1;
        const b = this.h - this.h0 - this.h1;
        this.r1 = Math.tan(a / b) / Math.PI * 180;
        this.len = Math.sqrt(a * a + b * b);
        this.start()
    }

    private async start() {
        await this.createBg();
        egret.Tween.get(this)
            .set({ scaleX: 0.1, scaleY: 0.1, alpha: .5, rotation: Monkey.RANGE / 3, x: 750 + 100 })
            .to({ y: this.targetY, x: this.targetX, scaleX: 1, scaleY: 1, alpha: 1 }, 1000, egret.Ease.getBackOut(.9))
            .wait(500)
            .call(this.startShaking, this);
    }

    startShaking() {
        this.addEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame, this);
        this.dispatchEvent(new egret.Event('onStartShaking'));
    }

    stopShaking() {
        if (this.hasEventListener(egret.Event.ENTER_FRAME))
            this.removeEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame, this);
    }

    stop(rotation = 0) {
        this.stopShaking();
        this._dir = 1;
        this.rotation = rotation;
    }

    private _dir = 1;
    onEnterFrame() {
        this.rotation += this._shakeSpeed * this._dir;
        if (this.rotation > Monkey.RANGE)
            this._dir = -1;
        if (this.rotation < -Monkey.RANGE)
            this._dir = 1;
        this.dispatchEvent(new egret.Event('pointUpdate', false, false, this.getPoint()))
    }

    getPoint() {
        const r = (this.r1 + this.rotation) / 180 * Math.PI;
        const a = Math.sin(r) * this.len;
        const b = Math.cos(r) * this.len;
        const y = b;
        const x = -a;
        return new egret.Point(x, y);
    }

    async createBg() {
        return new Promise(async (resolve) => {
            const picData = await RES.getResAsync('monkey_png');
            const pic = new egret.Bitmap(picData);
            this.addChild(pic);
            resolve(pic)
        });
    }
}