import { LayOUT } from "../utils/LayOUT";
import { LayoutControl } from "../Control/LayoutControl";
import {PanelBaseControl} from "../Control/PanelBaseControl";


/**
 *
 * @author 
 *
 */
export class ViewManager extends Laya.EventDispatcher
{
    
    private static ins: ViewManager;
    /**
     * 已注册的UI
     */
    private _views: any;

	public constructor() 
	{
        super();
        ViewManager.ins = this;
	}
	
	public static get Instance():ViewManager
	{
	    if( ViewManager.ins == null )
        {
            return new ViewManager();    
        }
        return ViewManager.ins;
	}

    public init():void
    {
        this._views = {};
        this.initEvent();
    }

    public initEvent():void
    {
    }
	
    /**
     *  view 视图对象类
     *  data 绑定数据 （ data 如果不为空，代表构造函数传参 ）
     *  layer 层级
     */
    public add( view:any,data:any = null,layer: string = LayOUT.UI ):any
	{
        if( view.key == null )
        {
            throw new Error("view have no key");
        }
        var type: string = view.key;
        if(this._views[type])
        {
            var itemview:fairygui.GComponent = this._views[type];
            return itemview;
        }
        var d: any;
        if(data != null )
        {
            d = new view(data);
        }
        else
        {
            d = new view();
        }
        d.viewKey = view;
        d.gameLayer = layer;
        LayoutControl.Instance.AddLayerByName( d,layer );
        this._views[type] = d;
        return d;
	}
    
    /**
     * 关闭界面
     * @param view 界面 
     * @param isbgclose 是否是点击背景关闭的状态 
     * @param isplayAnmo 是否播放关闭动画（ 主要用于强制关闭 ）
     */
    public close( view: any,isbgclose:boolean=false,isplayAnmo:boolean=true ):void
	{
        var type: string = view.key;
        var item: PanelBaseControl = this._views[type];
        if(!item) 
        {
            return;
        }
        LayoutControl.Instance.ClearLayerByName( item.gameLayer );
        if(isplayAnmo)
        {
            item.ExitView();
        }
        else
        {
            item.destory();
        }
        delete this._views[type];
	}

    public onresize( w:number,h:number ):void
    {
        if( this._views != null )
        {
            var itemview:PanelBaseControl;
            for( var item in this._views )
            {
                itemview = this._views[item];
                itemview.setSize( w,h );
            }
        }
    }
	
    public getView( view: any ):any
	{
        var type: string = view.key;
        return this._views[type];
	}
}
