import { LayerManager } from "./LayerManager";
import { GUIManager } from "./GUIManager";
import { Prefab, Node, loader } from "cc";
import { GUIMediator } from "./GUIMediator";


export default class GUIProxy{
    key:number;
    prefabName:string;
    prefab:Prefab;
    uiNode:Node;
    mediator:GUIMediator;
    /**
     * 状态 0 未加载  1加载中 2加载完成
     */
    state:number=0;

    /**
     * 是否显示
     */
    isShowing:boolean;

    data:any;

    constructor(key:number,prefabName:string){
        this.key=key;
        this.prefabName=prefabName;
    }

    /**
     * 显示(内部接口)
     * @param data 
     */
    Show(data?:any):void{
        this.data=data;
        this.isShowing=true;
        if(this.state==0){
            this.LoadUIAssetBundle();
        }else if(this.state==1){
            //加载中啥也不干
        }else{
            this.AddToLayer();
        }
    }

    /**
     * 内部接口
     */
    Hide():void{
        if(this.mediator){
            this.uiNode.active=false;
            this.mediator.OnHide();
        }
        this.isShowing=false;
    }

    /**
     * 添加到层上并显示
     */
    private AddToLayer():void{
        this.uiNode.active=true;
        this.mediator.OnShow(this.data);
    }

    private LoadUIAssetBundle(){
        this.state=1;
        loader.loadRes(this.prefabName, Prefab,this.OnLoadUIPrefabProgress.bind(this),this.OnLoadUIPrefabComplete.bind(this));
    }

    private OnLoadUIPrefabProgress(completedCount: number, totalCount: number, item: any):void{
        // console.log(this.prefabName+":"+(finish/total));
    }
    
    private OnLoadUIPrefabComplete(error: Error, assets:Prefab):void{
        if(error!=null){
            throw new Error("请检查UIConst中注册UI时的预制体路径是否正确："+this.prefabName);
        }
        this.prefab=assets;
        this.state=2;
        this.uiNode=cc.instantiate(this.prefab);
        this.mediator=this.uiNode.getComponent(GUIMediator);
        this.mediator.uiKey=this.key;
        //添加到层
        LayerManager.single.AddToLayer(this.mediator.LayerIndex,this.uiNode);
        if(this.isShowing){
            this.AddToLayer();
        }
    }

    /**
     * 获取UI所属层
     */
    get LayerIndex(){
        return 3;
    }
}