import ConfigManager from "../configs/ConfigManager";
import { EventDispatcher } from "../events/EventDispatcher";
import IInitiator from "./IInitiator";
import InitiatorEvent from "./InitiatorEvent";


/**
 * 配置表初始化
 */
export default class ConfigInitiator extends EventDispatcher implements IInitiator{

    private __assetBundleName:string;
    private __dir:string;

    constructor(assetBundleName:string,dir:string){
        super();
        this.__assetBundleName=assetBundleName;
        this.__dir=dir;
    }

    Start(): void {
        let bundle:cc.AssetManager.Bundle=cc.assetManager.getBundle(this.__assetBundleName);
        if(bundle==null){
            throw new Error("配置表资源包未加载："+this.__assetBundleName);
        }
        bundle.loadDir(this.__dir,cc.JsonAsset,this.LoadConfigProgress.bind(this),this.LoadConfigComplete.bind(this));
    }

    private  LoadConfigProgress(index:number,total:number):void{
        let progress:number=index/total;
        this.DispatchEvent(InitiatorEvent.EVENT_PROGRESS,progress);
    }

    private  LoadConfigComplete(err:Error,asset:cc.JsonAsset[]):void{
        if(err){
            this.DispatchEvent(InitiatorEvent.EVENT_ERROR,"配置表加载出错："+err);
            return;
        }
        ConfigManager.single.Init(asset);
        this.DispatchEvent(InitiatorEvent.EVENT_COMPLETE);
    }
    
    Destroy(): void {
        this.__assetBundleName=null;
        this.__dir=null;
    }
    
    GetName(): string {
        return "ConfigInitiator";
    }
}