/**
 * Created by adri1 on 2014/10/20.
 */
var ConfigManager=function(json){
    this.db=new Config("configlist.db");
    this.json=json;
}
ConfigManager.prototype={
    setConfig:function(modconfig){
        if(checkERROR(this.db.get(this.json.modid))){
            this.db.set(this.json.modid,new Object());
        }
        var configlist=this.db.get(this.json.modid);
        configlist[modconfig.id]=modconfig;
        this.db.set(this.json.modid,configlist);
    },
    delConfig:function(configid){
        delete this.db.get(this.json.modid)[configid];
        this.db.update();
    },
    getLocalConfig: function(configid){
        if(checkERROR(this.db.get(this.json.modid))){
            return null;
        }
        return this.db.get(this.json.modid)[configid];
    },
    getRemoteConfigList: function(){
        return this.json.configlist;
    },
    getRemoteConfig: function(i){
        return this.json.configlist[i];
    },
    delAllModConfig: function (modid,modname) {
        var cl=this.db.get(modid);
        if(checkERROR(cl)){
            return;
        }
        for(var configid in cl){
            var config=cl[configid];
            //路径不存在
            var savepath=config.savepath;
            if(checkERROR(savepath)){
                var filename=modname+"_"+config.dictionary.replace(/\//g, "_")+"_"+config.name;
                savepath = "download_mods/" + filename+".zip";
            }
            new CleverInstaller(getUniqueId(), modname+"_"+config.name, savepath, 'delete');
            delete this.db.get(modid)[configid];
        }
        this.db.update();
    },
    downloadConfig:function(id){
        var config = this.getRemoteConfig(id);
        if (checkERROR(config)) {
            customAlert("选择的插件不存在", "warning");
            return;
        }
        var url = config.url;
        var filename=this.json.modname+"_"+config.dictionary.replace(/\//g, "_")+"_"+config.name;
        var savepath = "download_mods/" + filename+".zip";
        config.savepath=savepath;
        customAlert(filename + "开始下载", "info");
        downloadCenter.add(url, savepath, filename, function (path) {
            var id=getUniqueId();
            new CleverInstaller(id, config.name, path, "install", config.id);
            cm.setConfig(config);
        });
    }
}