import MainScene from "../Scene/MainScene";
import GameComponent from "./GameComponent";
import { MUtils } from "../Global/MUtils";
import Collider from "./Collider";
import Game from "../Scene/Game";

export default class GameObject extends egret.DisplayObjectContainer {
    public name: string = "";
    private _position: egret.Point = new egret.Point();
    public get position() {
        this._position.x = this.x;
        this._position.y = this.y;
        return this._position;
    }

    public addComponent<T extends GameComponent>(cls: any): T {
        if (this.getComponent(cls) != null) {
            console.error("component is existent");
            return;
        }
        let ins = new cls(this);
        ins.enabled = true;
        this.componentList.push(ins);
        return ins;
    }

    public getComponent<T extends GameComponent>(cls: any): T {
        for (let i of this.componentList) {
            if (i instanceof cls) {
                return i as T;
            }
        }
        return null;
    }

    public removeComponent(cls: any) {
        for (let i of this.componentList) {
            if (i instanceof cls) {
                i.enabled = false;
                this.componentList = this.componentList.filter(e => e != i);
                return;
            }
        }
    }

    private componentList: GameComponent[] = [];
    protected context: Game = null;

    constructor(context?: Game) {
        super();
        this.anchorX = 0.5;
        this.anchorY = 0.5;
        this.context = context;
        this.touchEnabled = false;
        this.touchChildren = false;

        this.addEventListener(egret.Event.REMOVED_FROM_STAGE, this.disableAllComponents, this);
    }

    /**锚点X轴 */
    public get anchorX(): number {
        return this._anchorX;
    }
    public set anchorX(v: number) {
        this._anchorX = Math.clamp(v, 0, 1);
    }
    private _anchorX: number = 0;

    /**锚点Y轴 */
    public get anchorY(): number {
        return this._anchorY;
    }
    public set anchorY(v: number) {
        this._anchorY = Math.clamp(v, 0, 1);
    }
    private _anchorY: number = 0;

    public get posX(): number {
        return this.x + this.width * this.scaleX * this.anchorX;
    }
    public set posX(v: number) {
        this.x = v - this.width * this.scaleX * this.anchorX;
    }

    public get posY(): number {
        return this.y + this.height * this.scaleY * this.anchorY;
    }
    public set posY(v: number) {
        this.y = v - this.height * this.scaleY * this.anchorY;
    }

    protected disableAllComponents() {
        Object.keys(this.componentList).forEach(e => this.componentList[e].enabled = false);
    }

    protected enableAllComponents() {
        Object.keys(this.componentList).forEach(e => this.componentList[e].enabled = true);
    }

    public onCollisionEnter(other: Collider) {

    }

    public onCollisionStay(other: Collider) {

    }

    public onCollisionExit(other: Collider) {

    }
}