// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import GUIManager from "./GUIManager";
import GEngine from "../GEngine";
import GUIMediator from "./GUIMediator";
import LayerManager from "./LayerManager";

const {ccclass, property} = cc._decorator;


export default class GUIProxy{
    key:number;
    prefabName:string;
    prefab:cc.Prefab;
    uiNode:cc.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=cc.instantiate(this.prefab);
        this.mediator=this.uiNode.getComponent(GUIMediator);
        this.mediator.uiKey=this.key;
        //添加到层
        LayerManager.single.AddToLayer(this.mediator.LayerIndex,this.uiNode);
        this.mediator.OnShow(this.data);
    }

    private LoadUIAssetBundle(){
        this.state=1;
        GUIManager.single.AssetBundle.load(this.prefabName,cc.Prefab,this.OnLoadUIPrefabProgress.bind(this),this.OnLoadUIPrefabComplete.bind(this));
    }

    private OnLoadUIPrefabProgress(finish: number, total: number, item:cc.AssetManager.RequestItem):void{
        // console.log(this.prefabName+":"+(finish/total));
    }
    
    private OnLoadUIPrefabComplete(error: Error, assets:cc.Prefab):void{
        if(error!=null){
            throw new Error("请检查UIConst中注册UI时的预制体路径是否正确："+this.prefabName);
        }
        this.prefab=assets;
        this.state=2;
        if(this.isShowing){
            this.AddToLayer();
        }
    }

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