
import GameComponent from "./GameComponent";
import Collider from "../Phycics/Collider";
import Game from "./Game";

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 componentList: GameComponent[] = [];
    constructor() {
        super();
        // this.addEventListener(engine.Event.REMOVED_FROM_STAGE, this.disableAllComponents, this);
        this.mouseEnabled = false;
        this.mouseChildren = false;
    }

    /**销毁时禁用所有组件 */
    destroy() {
        super.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);
    }

    public onCollisionEnter(other: Collider) {

    }

    public onCollisionStay(other: Collider) {

    }

    public onCollisionExit(other: Collider) {

    }
}