Config=function(path){
    //"config/config.json"
    this.path=path;
    this.init=false;
    this.json={};
    this.writing=false;
    this.load();
}
Config.prototype= {

    load: function () {
        if (fs.existsSync(this.path)) {
            var data = fs.readFileSync(this.path, 'utf8');
            console.log(data.toString());
            try {
                this.json = JSON.parse(data);
            }catch(e){
                customAlert("加载"+this.path+"失败","warning");
            }

            this.init = true;
        }
    },

//写入配置文件
    update: function () {
        if(this.writing){
            console.log("update waiting");
            setTimeout(this.update(),100);
            return;
        }
        this.writing=true;
        var data = JSON.stringify(this.json); // '{"x":"bar"}'.
        console.log(this.path, "update:", data);
        fs.writeFileSync(this.path, data, 'utf8');
        this.writing=false;
    },

    get: function(k){
        return this.json[k];
    },
    set: function(k,v){
        if(this.writing){
            console.log("set waiting");
            setTimeout(this.set(k,v),100);
            return;
        }
        this.json[k]=v;
        this.update();
    }
}

var config = new Config("config/config.json");

//设置页面
function refreshConfig(){
	if ($("#configpage").html().length>0){
		$("#configpage").html("");
	}
	
	if(checkERROR(config.get('path'))){
		var path="未定义";
	}
	else{
		var path=config.get('path');
	}
	$("#configpage").load("config.html #config",function(data){
		if(checkERROR(config.get('replay'))||!config.get('replay')){
			$("#replayMonitorClose").parent().addClass("active");
		}else{
			$("#replayMonitorOpen").parent().addClass("active");
		}
		if(checkERROR(config.get('autochangegame'))||!config.get('autochangegame')){
			$("#autoChangeGameClose").parent().addClass("active");
		}else{
			$("#autoChangeGameOpen").parent().addClass("active");
		}
		$("#path").val(path);
        $("#path").change(function(){
            $("#custompath").show();
            $("#configpath").hide();
        })
        $("#custompath").click(function(){
            examineStarter($("#path").val(),function(){
                $("#custompath").hide();
                $("#configpath").show();
            });
        });
		$("#configpath").click(function(){
			chooseFile(function(path){
				var p=unescape(path);
				examineStarter(p,function(){
					$("#path").val(config.get('path'));
				});
			});
		});
		$("#replayMonitorOpen").click(function(){
			if(checkERROR(config.get('replay'))||!config.get('replay')){
				config.set('replay',true);
				$("#replayMonitorClose").parent().removeClass("active");
				$("#replayMonitorOpen").parent().addClass("active");
				customAlert("开启录像监控功能，请重启沙盘以生效","success");
			}
		});
		$("#replayMonitorClose").click(function(){
			if(checkERROR(config.get('replay'))||config.get('replay')){
				config.set('replay',false);
				$("#replayMonitorOpen").parent().removeClass("active");
				$("#replayMonitorClose").parent().addClass("active");
				customAlert("关闭录像监控功能，请重启沙盘以生效","success");
			}
		});
		
		$("#autoChangeGameOpen").click(function(){
			if(checkERROR(config.get('autochangegame'))||!config.get('autochangegame')){
                config.set('autochangegame',true);
				$("#autoChangeGameClose").parent().removeClass("active");
				$("#autoChangeGameOpen").parent().addClass("active");
				customAlert("开启游戏自动切换功能","success");
			}
		});
		$("#autoChangeGameClose").click(function(){
			if(checkERROR(config.get('autochangegame'))||config.get('autochangegame')){
                config.set('autochangegame',false);
				$("#autoChangeGameOpen").parent().removeClass("active");
				$("#autoChangeGameClose").parent().addClass("active");
				customAlert("关闭游戏自动切换功能","success");
			}
		});
	});
    getPatchList(examPatchList);
	$("#configpage").show();
}

//检测设置的游戏路径是否合适
function examineStarter(p,callback) {
    console.log("path", p);
    if (p.indexOf("WorldOfTanks.exe") == -1 && p.indexOf("WOTLauncher.exe") == -1) {
        p = p + "\\WOTLauncher.exe";
    }
    var e = fs.existsSync(p);
    if (e) {
        var pdir = p.substr(0, p.lastIndexOf("\\"));
        config.set('path',pdir);
        customAlert("游戏路径修改为:" + pdir, 'success');
        if (typeof(callback) == "function") {
            callback();
        }
    }
    else {
        customAlert("设置路径失败，找不到游戏启动程序", 'warning');
    }
    return e;
}


//获取安装位置
function getInstallPath() {
	//REG QUERY HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{1EAC1D02-C6AC-4FA6-9A44-96258C37C812}_is1 /v InstallLocation
	//获取地址
	var spawn=cp.spawn("apps\\exe\\RootFinder.exe",[]);
	spawn.stdout.on('data', function (data) {
		examineStarter(data.toString())
		return;
	});
	spawn.stderr.on('data', function (data) {
		customAlert("自动设置路径失败，请尝试手动设置路径",'warning')
		return;
	});
	//检验是否存在文件
	//不存在则读取录像播放位置
	//检验是否存在
	//不存在则提示用户选择
}
function getInstallBak(){
/*
	var cmd='reg.exe QUERY "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{1EAC1D02-C6AC-4FA6-9A44-96258C37C812}_is1" /v InstallLocation';
	var pr = cp.exec(cmd,{encoding: 'binary'},function(err, stdout, stderr){
		if(err != null){
			console.log('exec error:'+err);
		}
		console.log('stdout: ' + stdout);
		console.log('stderr: ' + stderr);
		if (stdout.length>0){
			var aOut=stdout.split("\n");
			for (var i in aOut) {
				var str=aOut[i].trim().split("\t");
				if (str[0]=="InstallLocation"){
					console.log("path",str[str.length-1]);
					config={path:str[str.length-1]}
					setConfig(config);
					return;
				}
				str=aOut[i].trim().split(" ");
				if (str[0]=="InstallLocation"){
					console.log("path",str[str.length-1]);
					config={path:str[str.length-1]}
					setConfig(config);
					return;
				}
			}
		}
	});
	*/
}
var versionDB=new Config("version.db");
// 更新沙盘
function getPatchList(callback) {
	// 1.获取补丁列表
	// 2.比对更新状态
	// 3.已更新的跳过
	// 4.未更新的非强制更新，加一条message
	// 5.未更新的强制更新直接提示用户更新
    //遍历.new文件,根据内容设置version.db
    if( fs.existsSync("update") ) {
        var files = fs.readdirSync("update");
        files.forEach(function(file,index){
            if(file.split('.')[1]=="new"){
                var ver=new Config('update/'+file);
                for (var i in ver.json){
                    versionDB.set(i,ver.get(i));
                }
                fs.unlinkSync('update/'+file);
            }
        });
    }
    if(!checkERROR(versionDB.get('沙盘主程序'))){
        document.title='战争沙盘 V'+versionDB.get('沙盘主程序')+" for "+newestVersion;
    }
	$.get("http://rank.kongzhong.com/ModDownload/action/PatchAction/patchList", function(data, status) {
		console.log("server version:" + data);
        try {
            var versionlist = JSON.parse(data);
            for (var ver in versionlist.patchlist) {
                var patch = versionlist.patchlist[ver];
                if (patch.url.indexOf("http") == -1) {
                    continue;
                }
                if (typeof(callback) == "function") {
                    callback(patch);
                }
            }
        }catch(e){
            customAlert("加载patchlist失败","warning")
        }
	});
}

function examinePatch(patch) {
    //下载过该类补丁
    if(!checkERROR(versionDB.get(patch.name))){
        //本地版本小于服务器版本
        if(versionDB.get(patch.name).version<patch.version){
            customAlert(patch.name+'有新补丁了，更新内容:<br/>'+patch.description,'warning')
        }
    }
}

function sortPatch(a,b)
{
	return Number(a.name) - Number(b.name)
}

function examPatchList(patch) {
    var local=versionDB.get(patch.name);
    var exist=false;
    if(!checkERROR(local)&&local>=patch.version){
        exist=true;
    }
    var test=false;
    if (patch.state == 2) {
        test = true;
    }
	var content = "<tr class='text "+(exist?"installedpatch":"")+"' id='patchtr"+patch.id+"'><td class='text patchname'>"
				+ patch.name
				+ "</td><td class='version text' >"+patch.version+"</td><td class='text'>"
				+ (test ? "<span class='label label-info'>小白鼠</span> "	: "")
				+ patch.description
				+ "</td><td class='oper'><button type='button' id='patchlist"
				+ patch.id
				+ "' class='btn patchbutton btn-primary'>安装补丁</button></td><td class='url hide'>"+patch.url+"</td></tr>";
		$("#patchbody").append(content);
		$("#patchlist" + patch.id).click(function() {
			var url=$(this).parent().parent().children(".url").text();
			var name=$(this).parent().parent().children(".patchname").text();
			var version=$(this).parent().parent().children(".version").text();
			customAlert(name+version+'版本补丁开始安装','success');
			updatePatch(url, name, version);
		});
		
		$("#showUpdated").click(function(){
			$(".installedpatch").toggle();
		})
}

function updatePatch(url, name, version) {
    //TODO
	console.log(url, name, version);
	var file = "update/"+name+version+".zip";
    downloadCenter.add(url,file,name,function(file) {
        monitorStop();
        patchUnzip(file,"./",function(){
            customAlert(name+'安装成功,请重启沙盘以确保生效','success');
        });
    });
}

function patchUnzip(file,dir,callback){
    dir=dir.replace(/\\/g,"\\\\");
    console.log("\"apps\\exe\\unzip.exe\" -d \""+dir+"\" -o "+file);
    var spawn=cp.exec("\"apps\\exe\\unzip.exe\" -d \""+dir+"\" -o "+file,{encoding: 'binary'},function(err, stdout, stderr){
        if(err != null){
            console.log('exec error:'+repairCharset(err));
            customAlert("解压失败:"+repairCharset(err)+"\n请手动解压沙盘目录\\"+file+"到"+(dir=="./"?"沙盘目录":dir),'danger');
            return;
        }
        if (stderr.length>0){
            console.log('stderr: ' + repairCharset(stderr));
            customAlert("解压失败，请手动解压沙盘目录\\"+file+"到"+(dir=="./"?"沙盘目录":dir),'danger');
            return;
        }
        console.log('stdout: ' + repairCharset(stdout));
        callback(file,dir);
    });
}