import { MouseEvent } from './../../engine/2d/events/MouseEvent';
import { Container } from "../../engine/2d/display";
import { RES } from "../RES";

/**
 * 
 */
export class Module extends Container {
    protected data: any;
    constructor(data?: any) {
        super();
        this.data = data;
        this.init();
    }
    /**
     * 初始化资源和皮肤
     */
    private init() {
        this.preLoadRes().then(
            () => {
                this.initUi();
                this.onLoaded && this.onLoaded();
            },
            () => {
                this.onLoadError && this.onLoadError();
            }
        );
    }
    /**
     * 提前加载的资源
     */
    protected preLoadRes() {
        return new Promise((resolve, reject) => {
            if (this.groupNames && this.groupNames.length) {
                var arr: Promise<any>[] = [];
                for (var i = 0; i < this.groupNames.length; i++) {
                    arr.push(RES.loadGroup(this.groupNames[i]))
                }
                Promise.all(arr).then(resolve, reject)
            } else {
                resolve()
            }
        })
    }

    /**
     * 初始化ui
     */
    protected initUi() {

    }

    /**
     * 资源加载完成后执行，用于场景及弹框控制
     */
    onLoaded: () => void;

    /**
     * 资源加载失败时执行，用于场景及弹框控制
     */
    onLoadError: () => void;

    /**
     * 可以有多个组
     */
    get groupNames(): string[] { return null }

    /**
     * 在构造函数后执行
     */
    start(data?: any) {
        this.initEvents();
    }

    /**
     * 添加事件
     */
    initEvents(): void {

    }

    /**
     * 移除事件
     */
    removeEvents(): void {

    }

    /**
     * 鼠标事件
     * @param enable 
     */
    protected enableMouseEvt(enable: boolean): void {
        this.mouseEnable = enable;
        this.mouseChildren = enable;
    }

    public onClick(target, func, scope?) {
        target.addEventListener(MouseEvent.CLICK, func, scope)
    }

    public removeClick(target, func, scope?) {
        target.removeEventListener(MouseEvent.CLICK, func, scope)
    }

    public destroy(): void {
        this.data = null;//看情况吧，有时候hidePanel后用了data，注意
        //移除事件
        this.removeEvents();
        //派发销毁事件，主要用于场景及弹框控制
        this.dispatchEvent("onDestroy");
        super.destroy();
    }
}