
import GUIProxy from './GUIProxy';

export class GUIManager{
    
    //UI 注册信息
    private m_guiMap:Map<number,GUIProxy>=new Map<number,GUIProxy>();
    //正在显示的UI
    private m_showing:Map<number,GUIProxy>=new Map<number,GUIProxy>();
    private m_showingList:GUIProxy[]=[];
    /**
     * 注册UI
     * @param key                全局唯一KEY
     * @param assetBundle        资源所在AssetBundle
     * @param packageName        包名称
     * @param resName            UI界面
     * @param mediatorClass      UI界面类
     */
    RegisterGUI(key:number,assetBundle:string,packageName:string,resName:string,mediatorClass:any):void{
        if(this.m_guiMap.has(key)){
            throw new Error("UI重复注册:"+key);
        }
        let guiProxy:GUIProxy=new GUIProxy(key,assetBundle,packageName,resName,mediatorClass);
        this.m_guiMap.set(key,guiProxy);
    }

    /**
     * 取消注册
     * @param key           UI 全局唯一KEY
     */
    Unregister(key:number):void{
        if(this.m_guiMap.has(key)==false){
            throw new Error("无法取消未注册的UI："+key);
        }
    }
    
    /**
     * 显示UI
     * @param key 
     * @param data 
     */
    Show(key:number,data?:any):void{
        if(this.m_guiMap.has(key)==false){
            throw new Error("未注册的UI："+key);
        }
        let guiProxy:GUIProxy;
        //已经显示
        if(this.m_showing.has(key)){
            return;
        }else{
            guiProxy=this.m_guiMap.get(key);
            guiProxy.Show(data);
            this.m_showing.set(key,guiProxy);
            this.m_showingList.push(guiProxy);
        }
    }

    /**
     * 隐藏UI
     * @param key 
     */
    Hide(key:number):void{
        if(this.m_guiMap.has(key)==false){
            throw new Error("未注册的UI："+key);
        }
        let guiProxy:GUIProxy;
        //已经显示
        if(this.m_showing.has(key)==false){
            return;
        }else{
            this.m_showing.delete(key);
            guiProxy=this.m_guiMap.get(key);
            guiProxy.Hide();
            let index:number=this.m_showingList.indexOf(guiProxy);
            this.m_showingList.splice(index,1);
        }
    }

    /**
     * 心跳
     * @param dt 
     */
    Tick(dt:number):void{
        let count:number=this.m_showingList.length;
        if(count==0){
            return;
        }
        for (let index = 0; index < count; index++) {
            const element = this.m_showingList[index];
            element.Tick(dt);
        }
    }

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