import GameComponent from "./GameComponent";
import GameObject from "./GameObject";
import PhycicsSystem from "./PhycicsSystem";
import Collider from "./Collider";
import MEvent from "../MComponents/MEvent";

/**物理组件
 * 更新游戏物体的移动旋转
 */
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 onMoved = new MEvent<(owner: GameObject, remove: () => void) => void>();

    /**物理更新
     * 目前基于帧
     */
    public onFixedUpdate() {
        this.velocity.x += this.acceleration.x;
        this.velocity.y += this.acceleration.y;
        if (this.velocity.length > 0) {
            this.moveTo(this.owner.position.add(this.velocity));
        }

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

    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.call(this.owner);
    }

    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];
    }
}