import {ResourceControl} from "./ResourceControl";
import {LocalData} from "../Data/LocalData";
import { Global } from "../Global";
import {GamePool} from "../PrefabControl/GamePool";
import { AssetPath } from "../Config/AssetPath";
import {TimerService} from "../Time/TimerService";
import Tab = Laya.Tab;
/*
* 资源管理器;
*/
export class ResDataControl implements TimerControl
{
    private static ins:ResDataControl;

    
    /**
     * 不缓存的包数据（ 预防界面上的状态设置错误 ）
     */
    private NoLiveData:any;

   

    constructor(){
        ResDataControl.ins = this;
    }

    public static get Instance():ResDataControl
    {
        if( ResDataControl.ins == null )
        {
            return new ResDataControl();
        }
        return ResDataControl.ins;
    }

    /**
     * 添加包
     * @param path 路径（ 事例：res/ui/ ）
     * @param pkgname 包名
     * @param isaddpackage 是否添加 
     * @param isCache 是否缓存
     */
    public AddPackByName(path:string,pkgname:string,isaddpackage:boolean = true,isCache:boolean = true):void
    {
        if( isaddpackage )
        {
            fairygui.UIPackage.addPackage(path + pkgname,pkgname);
        }
        this.AddLocalLiveData( pkgname,isCache );
    }

    public init():void
    {
        GamePool.Mark( LocalData.ResDicValue,LocalData );
        this.urlRes = {};
        this.packageRes = {};
        this.NoLiveData = { "loading":true,"main":true,"uicomponent":true};
        TimerService.Instance.addUpdateTarget(this);
    }

     /**
     * 清理资源缓存(Array)
     * @param urls 资源数组
     * @param packageName 包名
     */
    public RemoveResources( urls:Array<any>,packageName:string = "" ):void
    {
        if( packageName != "" )
        {
            fairygui.UIPackage.removePackage( packageName );
        }
        for( var s in urls )
        {
            this.RemoveResourcesByurl( urls[s].url,true );
        }
    }

    /************************************************ */
    private placeHSlider(): void {
        var hs:Laya.HSlider = new Laya.HSlider();
        hs.skin = "res/ui/hslider.png";

        hs.width = 300;
        hs.pos(50, 170);
        hs.min = 0;
        hs.max = 100;
        hs.value = 50;
        hs.tick = 1;

        Laya.stage.addChild(hs);
    }
    private placeVSlider(): void {
        var vs:Laya.VSlider = new Laya.VSlider();

        vs.skin = "res/ui/vslider.png";

        vs.height = 300;
        vs.pos(400, 50);
        vs.min = 0;
        vs.max = 100;
        vs.value = 50;
        vs.tick = 1;
       
        Laya.stage.addChild(vs);
    }
    /************************************************ */

    private _time:number = 0;
    public update( dt:number ):void
    {
        this._time += dt;
        if( this._time > this.CheckInterval ) //1分钟检查一次
        {
            if( ResourceControl.Instance.running ) //如果当前在加载中，延时1秒检测
            {
                this._time-=1000;
                return;
            }
            this.RefreshGroupRes();
            this._time = 0;
        }
    }

    /**
     * 清理资源缓存(url)
     * @param url 要清理的资源url
     * @param isClear 对于缓存池中的数据，当引用为0时，是否直接强制清除（ 如果为false,则等待缓存定时刷新时候再去判断 ）
     */
    public RemoveResourcesByurl( url:string,isClear:boolean = false ):void
    {
        if(this.urlRes.hasOwnProperty(url))
        {
            if( isClear )
            {
                
                Laya.loader.clearRes(url);
                delete this.urlRes[url];
            }
            else
            {
                this.urlRes[url]--;
            }
        }
        else
        {
            Laya.loader.clearRes(url);
        }
    }

    /**
     * 包资源池
     */
    private packageRes:any;


    

    private ClearLiveDataByPackName( pkgName:string ):void
    {
        if( this.packageRes[ pkgName ] )
        {
            var vo:LocalData = this.packageRes[ pkgName ];
            vo.clear();
            delete this.packageRes[ pkgName ];
        }
    }

 
    private ClearInterval:number = 50000;

    private CheckInterval:number = 20000;
     /**
     * url资源池
     */
    private urlRes:any;

    /**
     * 添加ui包
     * @param pkgname 包名
     * @param isaddpackage 是否创建uipackage
     * @param isCache 是否添加到组缓存中（ 如果添加，则参与定时清理的逻辑,常驻资源请勿设置为ture ）
     */
    public AddViewPackByName(pkgname:string,isaddpackage:boolean = true,isCache:boolean = true):void
    {
        if( isaddpackage )
        {
            if( pkgname == "main" )
            {
                fairygui.UIPackage.addPackage(AssetPath.res + AssetPath.subpacksgeui + pkgname,pkgname);
            }
            else
            {
                fairygui.UIPackage.addPackage(AssetPath.resources + AssetPath.ui + pkgname,pkgname);
            }
            
        }
        this.AddLocalLiveData( pkgname,isCache );
    }

    

    /**
     * 移除包
     * @param pkgname 包名
     * @param isclear 是否强制清除（ 如果为false则等待定时器判断清理，如果为true则强制清除 ）
     */
    public ClearPackByName(pkgname:string,isclear:boolean = false):void
    {
        if( pkgname == "" || pkgname == null )
        {
            return;
        }
        if( isclear )
        {
            
            fairygui.UIPackage.removePackage( pkgname );
            if( this.packageRes.hasOwnProperty( pkgname ) )
            {
                delete this.packageRes[pkgname];
            }
        }
        else
        {
            if( this.packageRes.hasOwnProperty( pkgname ) )
            {
                var vo:LocalData = this.packageRes[ pkgname ];
                if( vo )
                {
                    vo.ref--;
                }
            }
        }
    }

    private RefreshGroupRes():void
    {
        var nowTime:number = Laya.Browser.now();
        var s;
        if( this.packageRes )
        {
            var vo:LocalData;
            for( s in this.packageRes )
            {
                vo = this.packageRes[s];
                if( vo.ref <= 0 && (nowTime - vo.time) > this.ClearInterval )
                {
                    this.ClearPackByName( vo.packageName,true );
                    this.ClearLiveDataByPackName( vo.packageName );
                }
            }
        }
        //清理图片缓存
        if( this.urlRes )
        {
            var resourceurlPool:any = this.urlRes;
            for( s in resourceurlPool )
            {
                if( resourceurlPool[s] <= 0 )
                {
                    this.RemoveResourcesByurl( s,true );
                }
            }
        }
    }

    /******************************************************************* */
    private skins: Array<string> = ["res/ui/tab1.png", "res/ui/tab2.png"];
    private onSkinLoaded(): void {
        var tabA: Tab = this.createTab(this.skins[0]);
        tabA.pos(40, 120);
        tabA.labelColors = "#000000,#d3d3d3,#333333";

        var tabB: Tab = this.createTab(this.skins[1]);
        tabB.pos(40, 220);
        tabB.labelColors = "#FFFFFF,#8FB299,#FFFFFF";
    }

    private createTab(skin: string): Tab {
        var tab: Tab = new Tab();
        tab.skin = skin;

        tab.labelBold = true;
        tab.labelSize = 20;
        tab.labelStrokeColor = "#000000";

        tab.labels = "Tab Control 1,Tab Control 2,Tab Control 3";
        tab.labelPadding = "0,0,0,0";

        tab.selectedIndex = 1;
        Laya.stage.addChild(tab);

        return tab;
    }
   /******************************************************************* */


    /**
     * 获取已经加载过的数据
     * @param url 资源url
     * @param isCache 是否存储在缓存池中，默认为true
     */
    public GainResources( url:string,isCache:boolean = true ):any
    {
        if( isCache )
        {
            if(this.urlRes[url] == null)
            {
                this.urlRes[url] = 0;
            }
            this.urlRes[url]++;
        }
        return Laya.loader.getRes(url);
    }

    


    private AddLocalLiveData( pkgname:string,isCache:boolean ):void
    {
        if( isCache && !this.NoLiveData.hasOwnProperty( pkgname ) )
        {
            var vo:LocalData;
            if( !this.packageRes.hasOwnProperty( pkgname ) )
            {
                vo = GamePool.GetItem( LocalData.ResDicValue );
                vo.packageName = pkgname;
                this.packageRes[ pkgname ] = vo;
            }
            else
            {
                vo = this.packageRes[pkgname];
            }
            vo.ref++;
            vo.time = Laya.Browser.now();
        }
    }

   
}