import { EventDispatcher } from "../events/EventDispatcher";



export default class JLoader extends EventDispatcher
{
    public static EVENT_PROGRESS:string="JLoader.EventProgress";
    public static EVENT_ERROR:string="JLoader.EventError";
    public static EVENT_COMPLETE:string="JLoader.EventComplete";

    private packageName:string;
    private assetPath:string;
    private bundle:cc.AssetManager.Bundle;
    constructor(){
        super();
    }

    Load(packageName:string,assetPath:string):void{
        this.packageName=packageName;
        this.assetPath=assetPath;
        this.bundle=null;
        this.bundle=cc.assetManager.getBundle(this.packageName);
        if(this.bundle!=null){
            this.LoadAsset();
            return;
        }
        cc.assetManager.loadBundle(this.packageName,this.AssetBundleLoaded.bind(this));
    }

    GetContent(type:typeof cc.Asset):cc.Asset{
        return this.bundle.get(this.assetPath,type);
    }

    private AssetBundleLoaded(err:Error,bundle:cc.AssetManager.Bundle):void{
        if(err){
            cc.error(err);
            this.DispatchEvent(JLoader.EVENT_ERROR,err);
        }
        this.bundle=bundle;
        this.LoadAsset();
    }
    private LoadAsset():void{
        this.bundle.load(this.assetPath,this.AssetLoaded.bind(this));
    }

    private AssetLoaded(err:Error,asset:cc.Asset):void{
        if(err){
            cc.error(err);
            this.DispatchEvent(JLoader.EVENT_ERROR,err);
        }
        this.DispatchEvent(JLoader.EVENT_COMPLETE);
    }
}