import { _decorator, Component, Node } from 'cc';
const { ccclass, property } = _decorator;


export class LayerManager{
    /**
     * 层次根节点
     */
    private root:Node;

    /**
     * 层次
     */
    private layers:Node[];
    
    constructor(){
        
    }

    /**
     * 初始化
     * @param root 
     * @param layerCount 
     */
    Init(root:Node):void{
        this.root=root;
        let layer:Node;
        this.layers=[];
        for (let index = 0; index < this.root.children.length; index++) {
            this.layers[index]= this.root.children[index];
        }
    }

    /**
     * 添加内容到层
     * @param layerIndex 
     * @param node 
     */
    AddToLayer(layerIndex:number,node:Node):void{
        let layer:Node=this.layers[layerIndex];
        if(layer==null){
            throw new Error("找不到："+layerIndex+"层！");
        }
        layer.addChild(node);
    }

    /**
     * 从层上删除内容
     * @param layerIndex 
     * @param node
     */
    RemoveFormeLayer(layerIndex:number,node:Node):void{
        let layer:Node=this.layers[layerIndex];
        if(layer==null){
            throw new Error("找不到："+layerIndex+"层！");
        }
        layer.removeChild(node);
    }

    /**
     * 通过层索引获取层
     * @param layerIndex 
     */
    GetLayer(layerIndex:number){
        let layer:Node=this.layers[layerIndex];
        if(layer==null){
            throw new Error("找不到："+layerIndex+"层！");
        }
        return layer;
    }

    /**
     * 单例
     */
    private static instance:LayerManager;
    public static get single():LayerManager{
        if(this.instance==null){
            this.instance=new LayerManager();
        }
        return this.instance;
    }
}
