import { getResPath } from "../utils";

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;
    private 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 / 2, x: 750 + 100 })
            .to({ y: this.targetY, x: this.targetX, scaleX: 1, scaleY: 1, alpha: 1 }, 1000, egret.Ease.getBackInOut(.9))
            .wait(500)
            .call(this.startShaking, this);
    }

    startShaking() {
        this.addEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame, this);
    }

    stopShaking() {
        this.addEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame, this);
    }

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

    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() {
        let url = getResPath() + `resource/assets/startScene/monkey.png`;
        return new Promise((resolve) => {
            RES.getResByUrl(url, (picData) => {
                const pic = new egret.Bitmap(picData);
                this.addChild(pic);
                resolve(pic)
            }, this, RES.ResourceItem.TYPE_IMAGE);
        });
    }
}