import GameComponent from "../Game/GameComponent";
import GameObject from "../Game/GameObject";
import PhycicsSystem from "./PhycicsSystem";
import Collider from "./Collider";
import { DataMgr } from "../Mgr/DataMgr";

export default class Physics extends GameComponent {
    /**旋转速度 
     * @单位 （弧度制）度/帧
     * @方向 正值表示顺时针旋转，负表示逆时针旋转
     **/
    public rotateVelocity: number = 0;
    /**每帧速率的增量
     * x坐标表示对应坐标轴方向上速率的增量（标量）
     * @单位 像素/帧
     **/
    public acceleration: engine.Point = new engine.Point();
    /**速度 单位：像素/帧 */
    public velocity: engine.Point = new engine.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 | engine.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() {
        DataMgr.game._phycicsSystem.remove(this);
    }
    protected onEnabled() {
        DataMgr.game._phycicsSystem.add(this);
    }

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