import LayerManager from "../gui/layers/LayerManager";
import NoticeView from "./NoticeView";



export default class NoticeManager
{
    private __viewClassMap:Map<number,any>=new Map<number,any>();
    private __Pool:Map<number,NoticeView[]>=new Map<number,NoticeView[]>();

    /**
     * 注册
     * @param type 
     * @param viewClass 
     */
    Register(type:number,viewClass:any):void{
        this.__viewClassMap.set(type,viewClass);
    }

    /**
     * 显示提示
     * @param data 
     * @param type 
     * @param posType 
     */
    ShowPrompt(data:any,type:number,posType:number,layerIndex:number=9):void{
        let view:NoticeView=this.CreateByPool(type);
        view.Update(data);
        view.StartAnimation();
        LayerManager.single.AddToLayer(layerIndex,view.GetView());
    }

    private CreateByPool(type:number):NoticeView{
        let list:NoticeView[];
        if(this.__Pool.get(type)!=null){
            list=this.__Pool.get(type);
            if(list.length>0){
                return list.shift();
            }
        }
        if(this.__viewClassMap.has(type)==false){
            throw new Error("找不到对应的Notice View"+type);
        }
        let viewClass=this.__viewClassMap.get(type);
        let view:NoticeView=new viewClass();
        view.type=type;
        if(view instanceof NoticeView){
            return view;
        }else{
            throw new Error("Notice 注册的类型必须是NoticeView 的子类！");
        }
    }

    Recycle(value:NoticeView):void{
        if(value.GetView().parent!=null){
            value.GetView().removeFromParent();
        }
        let list:NoticeView[];
        if(this.__Pool.get(value.type)!=null){
            list=this.__Pool.get(value.type);
        }else{
            list=[];
            this.__Pool.set(value.type,list);
        }
        if(list.indexOf(value)>=0){
            throw new Error("重复回收！");
        }
        list.push(value);
    }

    private static __instance:NoticeManager;
    public static get single():NoticeManager{
        if(this.__instance==null){
            this.__instance=new NoticeManager();
        }
        return this.__instance;
    }
}