import { find, instantiate, Node, Prefab } from "cc";
import { BaseLayer } from "../../common/BaseLayer";
import { constants } from "../data/constants";
import { resManager } from "./resManager";


export class layerManager {

    private static _instance: layerManager;
    private constructor() { }
    public static get instance(): layerManager {
        if (!this._instance) {
            this._instance = new layerManager();
        }
        return this._instance;
    }

    layer1: Node;
    layerHint: Node;

    loadLayers(onProgress?: Function, onComplete?: Function) {
        let arr = [
            constants.layers.StartLayer.path,
            constants.layers.LevelLayer.path,
        ];
        resManager.instance.loadAssetByPathArr(constants.bundles.common.name, arr, Prefab, onProgress, onComplete);
    }

    init(layer1: Node, layerHint: Node) {
        this.layer1 = layer1;
        this.layerHint = layerHint;

    }

    createNotice(content) {
        // 显示一条提示信息
        let noticeLayer = find(constants.layers.NoticeLayer.name, this.layerHint);
        if (noticeLayer) {
            noticeLayer.getComponent(constants.layers.NoticeLayer.name).createNotice(content);
        }
    }

    openLayer(layer: any, obj?: any, cb?: Function) {
        resManager.instance.loadAsset(layer.bundle, layer.path, Prefab, null, (err, prefab) => {
            if (err) {
                console.log("LayerManager.openLayer error:" + err.message, layer, err);
                return;
            }
            let name = layer.name;
            let node = instantiate(prefab);
            let com = node.addComponent(name);
            com.obj = obj;
            com.cb = cb;
            com.layerName = name;

            if (layer.name == constants.layers.NoticeLayer.name) {
                node.parent = this.layerHint;
            } else {
                node.parent = this.layer1;
            }

            console.log("openLayer " + name, obj);
        });
    }

    closeLayer(layer: BaseLayer) {
        let layerName = layer.layerName;
        layer.node.destroy();
    }

}

