/**
 * Created by adri1 on 2014/10/20.
 */
var ConfigManager=function(){
    this.db=new Config("configlist.db");
    this.json=null;
}
ConfigManager.prototype={
    setConfig:function(modid,config){
        if(checkERROR(this.db.get(modid))){
            this.db.set(modid,new Object());
        }
        var configlist=this.db.get(modid);
        configlist[config.configid]=config;
        this.db.set(modid,configlist);
    },
    delConfig:function(modid,configid){
        delete this.db.get(modid)[configid];
        this.db.update();
    },
    getLocalConfig: function(modid,configid){
        if(checkERROR(this.db.get(modid))){
            return null;
        }
        return this.db.get(modid)[configid];
    },
    getRemoteConfigList: function(modid){
        if(checkERROR(this.json)){
            return null
        }
        return this.json[modid];
    },
    getRemoteConfig: function(modid,configid){
        for (var i in this.json[modid]){
            if(this.json[modid][i].configid==configid){
                return this.json[modid][i];
            }
        }
        return null;
    },
    getRemoteConfigById: function(configid){
        for(var modid in this.json){
            for (var i in this.json[modid]){
                if(this.json[modid][i].configid==configid){
                    return this.json[modid][i];
                }
            }
        }
        return null;
    },
    loadRemoteConfig: function(){
        $.get("http://rank.kongzhong.com/ModDownload/action/ConfigAction/allConfigList",
        function(data, status) {
            try {
                configManager.json=data;
                var n=0;
                var title="";
                for(var id in configManager.db.json){
                    var cl=configManager.db.get(id);
                    for(var configid in cl){
                        if(configManager.getRemoteConfig(id,configid)!=null&&cl[configid]['updatetime']['time']<configManager.getRemoteConfig(id,configid)['updatetime']['time']){
                            n++;
                            //TODO
                            title+=configManager.getRemoteConfig(id,configid)['configname']+"\n";
                        }
                    }
                }
                if(n>0){
                    var cu = '&nbsp;<span class="badge btn-primary" title="'+n+'个可更新配置文件\n'+title+'" id="newconfig">' + n + '</span>';
                    $("#modlistbutton").append(cu);
                }
            } catch (e) {
                console.log(e);
            }
        });
    },
    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+config.ext;
            }
            if(fs.existsSync(savepath)) {
                new CleverInstaller(getUniqueId(), modname + "_" + config.name, savepath, 'delete', true);
            }
            delete this.db.get(modid)[configid];
        }
        this.db.update();
    },
    installAllModConfig: 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+config.ext;
                return;
            }
            if(fs.existsSync(savepath)) {
                new CleverInstaller(getUniqueId(), modname + "_" + config.name, savepath, 'install', true);
            }
        }
    },
    downloadConfig:function(modid,configid){
        var config = this.getRemoteConfig(modid,configid);
        var mod=modManager.getRemoteMod(modid);
        if (checkERROR(config)) {
            customAlert("选择的插件不存在", "warning");
            return;
        }
        var url = "http://rank.kongzhong.com/ModDownload/action/ConfigAction/download?configid="+configid;
        var filename=mod.name+"_"+config.dictionary.replace(/\//g, "_")+"_"+config.configname;
        var savepath = "download_mods/" + filename+config.ext;
        config.savepath=savepath;
        customAlert(filename + "开始下载", "info");
        downloadCenter.add(url, savepath, filename, function (paths) {
            var uid=getUniqueId();
            new CleverInstaller(uid, config.configname, paths, "install",true);
            if(savepath.indexOf('.otf')==-1 && savepath.indexOf('.ttf')==-1) {
                configManager.setConfig(modid, config);
            }
        });
    }
}
var configManager=new ConfigManager();

function showConfigList(modid){
    var mod=modManager.getRemoteMod(modid);

    var div='<div class="modal-dialog modal-lg">';
    div+='<div class="modal-content">';

    div+='<div class="modal-header">';
    div+='<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>';
    div+='<h4 class="modal-title" id="myModalLabel">'+mod.name+'可选配置文件</h4>';
    div+='<div class="hide modid">' + modid + '</div></div>';
    //body
    div+='<div class="modal-body">';
    var configlist=configManager.getRemoteConfigList(modid);
    if(checkERROR(configlist)){
        customAlert("配置列表正在读取中，请稍后重试");
        $('#modModal').modal('hide')
        return;
    }
    div+='</div>';

    div+='</div></div>';
    $("#modModal").html(div);
	for (var i in configlist) {
		var config=configlist[i];
		if($("#"+config.dictionary).length==0){
			$(".modal-body").append("<fieldset style='cursor: pointer;margin-bottom:30px;' id='"+config.dictionary+"'><legend style='color:red;'>"+config.dictionary+"</legend></fieldset>");
		}
		var isnew=false;
		var installed=false;
		if(modid in configManager.db.json){
			if(config.configid in configManager.db.json[modid]){
				if(configManager.getLocalConfig(modid,config.configid)['updatetime']['time']<config['updatetime']['time']){
					isnew=true;
				}
				installed=true;
			}
		}
		var fieldset='';
		fieldset += '<div class="row config">';
		fieldset += '<div class="col-xs-offset-1 col-xs-3"><h3 class="panel-title">'+config.configname+(installed?'<span class="label label-success">已安装</span>':'')+'</h3>'+(isnew?'<span class="pull-right label label-danger">更新</span>':'')+'<h5>总下载:' + config.down + '次</h5><h5>发布者:' + config.publisher + '</h5>'+'<button type="button" class="btn btn-sm btn-success configinstall">下载安装</button>'+(installed?'<button type="button" class="btn btn-sm btn-warning configdelete">删除记录</button>':'')+'</div>';
		fieldset += '<div class="col-xs-4"><h5>'+config.description+'</h5></div>';
		fieldset += '<div class="col-xs-4" style="text-align: center;"><img class="configpic" src="' + config.image + '"></div>';
		fieldset += '<div class="hide configid">' + config.configid + '</div>';
		fieldset += '</div>';

		fieldset += '<div class="col-xs-3 title">'+(installed?'<span class="label label-success">已安装</span>':'')+config.configname+(isnew?'<span class="pull-right label label-danger">更新</span>':'')+'</div>';
		fieldset += '</div>'
		$("#"+config.dictionary).append(fieldset);
	}
    $("fieldset legend").click(function(){
        $(this).parent().children('.config').toggle();
        $(this).parent().children('.title').toggle();
    });
    $("fieldset .title").click(function(){
        $(this).parent().children('.config').toggle();
        $(this).parent().children('.title').toggle();
    });
    $(".configinstall").click(function(){
        var modid=$(".modid").text();
        var configid=$(this).parent().parent().children('.configid').text();
        configManager.downloadConfig(modid,configid);
    });
    $(".configdelete").click(function(){
        var modid=$(".modid").text();
        var configid=$(this).parent().parent().children('.configid').text();
        configManager.delConfig(modid,configid);
        showConfigList(modid)
    });
}