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;
    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.createBg();
    }

    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 static RANGE = 30;
    private _shakeSpeed = .5;
    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);
        });
    }
}