
import GameComponent from "./GameComponent";

export default class GameObject extends engine.Container {
    public name: string = "";
    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 _anchorOffsetX: number = 0;
    public get anchorOffsetX(): number {
        return this._anchorOffsetX;
    }
    public set anchorOffsetX(v: number) {
        this._anchorOffsetX = v;
    }


    private _anchorOffsetY: number = 0;
    public get anchorOffsetY(): number {
        return this._anchorOffsetY;
    }
    public set anchorOffsetY(v: number) {
        this._anchorOffsetY = v;
    }



    private componentList: GameComponent[] = [];
    constructor() {
        super();
        // this.addEventListener(engine.Event.REMOVED_FROM_STAGE, this.disableAllComponents, this);
        this.mouseEnabled = false;
        this.mouseChildren = false;
    }

    /**销毁时禁用所有组件 */
    dispose() {
        this.destroy();
        this.disableAllComponents();
    }

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