import GameComponent from "./GameComponent";
import GameObject from "./GameObject";
import PhycicsSystem from "./PhycicsSystem";
import Collider from "./Collider";
import DebugMgr from "../Mgr/DebugMgr";

export default class Physics extends GameComponent {
    /**旋转速度 
     * @单位 （弧度制）度/帧
     * @方向 正值表示顺时针旋转，负表示逆时针旋转
     **/
    public rotateVelocity: number = 0;
    /**每帧速率的增量
     * x坐标表示对应坐标轴方向上速率的增量（标量）
     * @单位 像素/帧
     **/
    public acceleration: egret.Point = new egret.Point();
    /**速度 单位：像素/帧 */
    public velocity: egret.Point = new egret.Point();

    public get collider() {
        return this._collider;
    }
    public set collider(v: Collider) {
        this._collider = v;
        v.physics = this;
    }
    public _collider: Collider = null;

    public onFixedUpdate(dtFactor: number) {
        this.velocity.x += this.acceleration.x * dtFactor;
        this.velocity.y += this.acceleration.y * dtFactor;
        if (this.velocity.length > 0) {
            this.moveTo(
                this.owner.x += this.velocity.x * dtFactor,
                this.owner.y += this.velocity.y * dtFactor
            );
        }

        //旋转
        if (this.rotateVelocity != 0) {
            this.owner.rotation += this.rotateVelocity * dtFactor;
        }
    }

    public moveTo(x: number | egret.Point, y?: number) {
        if (typeof x == "number") {
            if (!y) {
                console.error("invalid param");
                return;
            }
            this.owner.x = x;
            this.owner.y = y;
        } else {
            this.owner.x = x.x;
            this.owner.y = x.y;
        }

        this.onMoved && this.onMoved(this.owner);
    }

    public onMoved: (owner: GameObject) => void;

    protected onDisabled() {
        PhycicsSystem.instance.remove(this);
    }
    protected onEnabled() {
        PhycicsSystem.instance.add(this);
    }

    public onColliderResize(collider: Collider) {
        let center = collider.getCenter();
        this.owner.anchorOffsetX = center[0];
        this.owner.anchorOffsetY = center[1];
    }
}