/*
* name;
*/
import Handler = Laya.Handler;
import {ResDataControl} from "./ResDataControl";
import { Global } from "../Global";
import { DispatcherManager } from "../utils/DispatcherManager";
import {RecConfigs} from "../Config/RecConfigs";
export class ResourceControl extends Laya.EventDispatcher
{
    private _configs: Array<any>;
    private _onConfigComplete: Function;
    private _onConfigProgress: Function; 
    private _onConfigCompleteTarget: any;
    private _groups: any;
    private _groupIndex: number = 0;
    public running:Boolean = false;
    private _nowLoadData:any;
    

    private static ins:ResourceControl;

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

    public init():void
    {
        this._configs = new Array<any>();
        this._groups = {};
        Laya.loader.retryNum = 4;
        Laya.loader.on(Laya.Event.ERROR, this, this.onError);
        Laya.loader.on("errorsMsg", this, this.errorsMsghandler);
        Laya.loader.on("gameerrorsMsg", this, this.gameerrorsMsghandler);
    }

    private onLoadConfigComplete():void
    {
        if( this._onConfigCompleteTarget != null && this._onConfigComplete != null )
        {
            this._onConfigComplete.call( this._onConfigCompleteTarget );
        }
    }

    private errorsMsghandler( msg:string ):void
    {
        DispatcherManager.dispatchEvent( "loadfailEvent",msg );
    }

    private gameerrorsMsghandler( msg:string ):void
    {
        DispatcherManager.dispatchEvent( "gameserrosEvent",msg );
    }

    /**
     * 加载资源组
     * @param groupName 组名
     * @param onResourceLoadTarget 作用域
     * @param ResourceLoadComplete 完成事件
     * @param onResourceProgress   加载进度事件
     * @param isShow               是否显示加载状态
     */
    public loadGroup(groupName:string,onResourceLoadTarget:any,ResourceLoadComplete:Function,onResourceProgress:Function = null,isShow:Boolean = true,args:any=null)
    {
        // Debuger.log(groupName);
        var data:any = {};
        data.complete = ResourceLoadComplete;
        data.completeTarget = onResourceLoadTarget;
        data.progress = onResourceProgress;
        data.urls = RecConfigs.Instance.ResDic[ groupName ];
        data.isShow = isShow;
        data.args=args;
        data.type = "group";
        data.resouseType = "2D";
        this._configs.push( data );
        this.loadStart();
    }

    /**
     * 加载单个资源
     * @param url 资源url
     * @param type 资源类型
     * @param onResourceLoadTarget 作用域
     * @param ResourceLoadComplete 完成事件
     * @param onResourceProgress 加载进度事件
     * @param isShow 是否显示加载状态
     */
    public Loader( url:any, type:string,onResourceLoadTarget:any,ResourceLoadComplete:Function,onResourceProgress:Function = null,isShow:Boolean = true,args:any=null ):void
    {
        var data:any = {};
        data.complete = ResourceLoadComplete;
        data.completeTarget = onResourceLoadTarget;
        data.progress = onResourceProgress;
        data.urls = [{url:url,type:type}];
        data.isShow = isShow;
        data.args=args;
        data.type = "single";
        data.resouseType = "2D";
        this._configs.push( data );
        this.loadStart();
    }

    /**
     * 加载数组资源
     * @param urls 
     * @param onResourceLoadTarget 
     * @param ResourceLoadComplete 
     * @param onResourceProgress 
     * @param isShow 
     */
    public Loaders( urls:Array<any>, onResourceLoadTarget:any,ResourceLoadComplete:Function,onResourceProgress:Function = null,isShow:Boolean = true,args:any=null ):void
    {
        var data:any = {};
        data.complete = ResourceLoadComplete;
        data.completeTarget = onResourceLoadTarget;
        data.progress = onResourceProgress;
        data.urls = urls;
        data.isShow = isShow;
        data.type = "arr";
        data.args=args;
        data.resouseType = "2D";
        this._configs.push( data );
        this.loadStart();
    }

    /**
     * 要加载的总数量
     */
    private _loadNum:number = 0;
    /**
     * 已经加载的数量
     */
    private _loadedNum:number = 0;

    private _preloadNum:number = 0;

    private _cut:number = 0;

    private _nowLoadArr:Array<any> = null;
    /**
     * 加载资源数组，此加载方法会单个加载数组内的资源，用于显示两个进度条（ 一个总进度条，一个单个资源进度条 ）
     * @param urls 
     * @param onResourceLoadTarget 
     * @param ResourceLoadComplete 
     * @param onResourceProgress 
     * @param isShow 
     */
    public loaderArr(urls:Array<any>, onResourceLoadTarget:any,ResourceLoadComplete:Function,onResourceProgress:Function = null,cut:number = 3):void
    {
        var data:any = {};
        data.complete = ResourceLoadComplete;
        data.completeTarget = onResourceLoadTarget;
        data.progress = onResourceProgress;
        data.urls = urls;
        data.isShow = false;
        data.type = "loaderArr";
        data.cut = cut;
        data.resouseType = "2D";
        this._configs.push( data );
        this.startLoad1();
    }

    private startLoad1():void
    {
        if( !this.running && this._configs.length > 0 )
        {
            this._nowLoadData = this._configs.shift();
            this._nowLoadArr = (this._nowLoadData.urls as Array<any>).concat().reverse();
            this._loadNum = this._nowLoadArr.length;
            this._loadedNum =0;
            this._preloadNum = this._loadedNum;
            this._cut = Number(this._nowLoadData.cut);
            this.loadStart1();
        }
    }

    private loadStart1():void
    {
        if( this.running )
        {
            return;
        }
        if( this._nowLoadArr && this._nowLoadArr.length > 0 )
        {
            this.running = true;
            var needArr:Array<any>;
            if( this._nowLoadArr.length > this._cut )
            {
                needArr = this._nowLoadArr.splice( 0,this._cut );
            }
            else
            {
                needArr = this._nowLoadArr.splice( 0 );
            }
            this._cut = needArr.length;
            this._preloadNum = this._loadedNum;
            this.onLoadingArr( 0 );
            var resouseType:string = this._nowLoadData.resouseType;
            if(resouseType == "2D"||resouseType==null)
            {
                Laya.loader.load(needArr, Handler.create(this, this.onLoadCompleteArr),Handler.create(this, this.onLoadingArr,null, false));
            }
            else
            {
                Laya.loader.create(needArr, Handler.create(this, this.onLoadCompleteArr),Handler.create(this, this.onLoadingArr,null, false));
            }
        }
        else
        {
            this._nowLoadData = null;
            this.startLoad1();
        }
    }

    private onLoadingArr(value:number ):void
    {
        this._loadedNum = this._preloadNum + value*this._cut;
        if( this._nowLoadData )
        {
            var allvalue:number = Math.ceil((this._loadedNum / this._loadNum )*100);
            if( this._nowLoadData.progress != null )
            {
                this._nowLoadData.progress.call( this._nowLoadData.completeTarget,allvalue,Math.floor(value*100) );
            }
        }
    }

    private onLoadCompleteArr():void
    {
        this.onLoadingArr( 1 );
        this._loadedNum = this._preloadNum + this._cut;
        this.running = false;
        if( this._loadedNum == this._loadNum )
        {
            if( this._nowLoadData && this._nowLoadData.complete )
            {
                this._nowLoadData.complete.call(this._nowLoadData.completeTarget);
            }
        }
        Laya.timer.callLater( this, this.loadStart1 );
        // this.loadStart1();
    }

    private loadStart():void
    {
        if( this.running || this._configs.length == 0 )
        {
            return;
        }
        this.running = true;
        this._nowLoadData = this._configs[0];
        var arr:Array<any> = this._nowLoadData.urls;
        var isShow:boolean = this._nowLoadData.isShow;
        if( isShow )
        {
            fairygui.GRoot.inst.showModalWait();
        }
        var resouseType:string = this._nowLoadData.resouseType;
        if( arr != null )
        {
            if(resouseType == "2D"||resouseType==null)
            {
                Laya.loader.load(arr,Handler.create(this, this.onLoadComplete),Handler.create(this, this.onLoading, null, false));
            }
            else
            {
                Laya.loader.create(arr,Handler.create(this, this.onLoadComplete),Handler.create(this, this.onLoading, null, false));
            }
        }
    }

    // 加载进度侦听器
    private onLoading(progress: number): void 
    {
        if( this._nowLoadData )
        {
            progress = Math.ceil( Number(progress * 100) );
            if( this._nowLoadData.progress != null )
            {
                this._nowLoadData.progress.call( this._nowLoadData.completeTarget,progress );
            }
        }
    }

    private onLoadComplete(args:any=null):void
    {
        fairygui.GRoot.inst.closeModalWait();
        if( this._nowLoadData && this._nowLoadData.complete )
        {
            if(this._nowLoadData.args){
                this._nowLoadData.complete.call(this._nowLoadData.completeTarget,this._nowLoadData.args);
            }else{
                this._nowLoadData.complete.call(this._nowLoadData.completeTarget);
            }
        }
        this.running = false;
        this._nowLoadData = null;
        this._configs.shift();
        this.loadStart();
    }

    private onError(err: String):void
    {
        fairygui.GRoot.inst.closeModalWait();
    }

    /**
     * 加载3D单个资源
     * @param url 资源url
     * @param type 资源类型
     * @param onResourceLoadTarget 作用域
     * @param ResourceLoadComplete 完成事件
     * @param onResourceProgress 加载进度事件
     * @param isShow 是否显示加载状态
     */
    public Loader3D( url:any, type:any,onResourceLoadTarget:any,ResourceLoadComplete:Function,onResourceProgress:Function = null,isShow:Boolean = true ):void
    {
        var data:any = {};
        data.complete = ResourceLoadComplete;
        data.completeTarget = onResourceLoadTarget;
        data.progress = onResourceProgress;
        data.urls = [{url:url,type:type}];
        data.isShow = isShow;
        data.type = "single";
        data.resouseType = "3D";
        this._configs.push( data );
        this.loadStart();
    }

    /**
     * 加载3D资源组
     * @param groupName 组名
     * @param onResourceLoadTarget 作用域
     * @param ResourceLoadComplete 完成事件
     * @param onResourceProgress   加载进度事件
     * @param isShow               是否显示加载状态
     */
    public loadGroup3D(groupName:string,onResourceLoadTarget:any,ResourceLoadComplete:Function,onResourceProgress:Function = null,isShow:Boolean = true,args:any=null)
    {
        var data:any = {};
        data.complete = ResourceLoadComplete;
        data.completeTarget = onResourceLoadTarget;
        data.progress = onResourceProgress;
        data.urls = RecConfigs.Instance.ResDic[ groupName ];
        data.isShow = isShow;
        data.args=args;
        data.type = "group";
        data.resouseType = "3D";
        this._configs.push( data );
        this.loadStart();
    }

    /**
     * 加载资源数组，此加载方法会单个加载数组内的资源，用于显示两个进度条（ 一个总进度条，一个单个资源进度条 ）
     * @param urls 
     * @param onResourceLoadTarget 
     * @param ResourceLoadComplete 
     * @param onResourceProgress 
     * @param isShow 
     */
    public loader3DArr(urls:Array<any>, onResourceLoadTarget:any,ResourceLoadComplete:Function,onResourceProgress:Function = null,isshow:boolean = false,args:any=null):void
    {
        var data:any = {};
        data.complete = ResourceLoadComplete;
        data.completeTarget = onResourceLoadTarget;
        data.progress = onResourceProgress;
        data.urls = urls;
        data.isShow = isshow;
        data.args=args;
        data.type = "loaderArr";
        data.resouseType = "3D";
        this._configs.push( data );
        this.loadStart();
    }

    /**
     * 加载特效
     * @param groupName 
     * @param onResourceLoadTarget 
     * @param ResourceLoadComplete 
     * @param args 
     */
    public loadEffect( groupName:string,onResourceLoadTarget:any,ResourceLoadComplete:Function,args:any=null ):void
    {
        var urls:Array<any> = RecConfigs.Instance.ResDic[ groupName ];
        if( urls && urls.length > 0 )
        {
            Laya.loader.load(urls,Handler.create( onResourceLoadTarget,ResourceLoadComplete,[args] ));
        }
    }
}