Config=function(paths){
    //"config/config.json"
    this.path=paths;
    if(!fs.existsSync(path.dirname(paths))) {
        fs.mkdirSync(path.dirname(paths), 0755);  //位置不存在时创建
    }
    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;
    },
    remove: function(k){
        delete this.json[k];
        this.update();
    },
    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(){
	checkNowPage("systemconfig",true);
	$("#configpage").show();
	if ($("#configpage").html().length>0){
		$("#configpage").html("");
	}
	var paths;
	if(checkERROR(config.get('path'))){
		paths="未定义";
	}
	else{
		paths=config.get('path');
	}
	$("#configpage").load("config.html #config",function(data){
        if(checkNowPage("systemconfig",false)){
            return;
        }
		if(checkERROR(config.get('replay'))||!config.get('replay')){
			$("#replayMonitorClose").parent().addClass("active");
		}else{
			$("#replayMonitorOpen").parent().addClass("active");
		}
        if(checkERROR(config.get('bakUnzip'))||!config.get('bakUnzip')){
            $("#bakUnzipClose").parent().addClass("active");
        }else{
            $("#bakUnzipOpen").parent().addClass("active");
        }

        if(!checkERROR(config.get("gameversion"))){
            $("#gamever").val(config.get("gameversion"));
        }
		$("#path").val(paths);
        $("#path").change(function(){
            $("#custompath").show();
            $("#configpath").hide();
        });


        $("#custompath").click(function(){
            examineStarter($("#path").val(),function(){
                $("#custompath").hide();
                $("#configpath").show();
            });
        });
		$("#configpath").click(function(){
			chooseFile(function(paths){
				var p=unescape(paths);
				examineStarter(p,function(){
					$("#path").val(config.get('path'));
				});
			});
		});
        $("#gamever").change(function(){
            $("#customVer").show();
        })
        $("#customVer").click(function(){
            config.set("gameversion",$("#gamever").val());
            customAlert("已设置当前游戏版本为"+config.get("gameversion"),"success");
            $("#customVer").hide();
        });
		$("#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");
			}
		});
        $("#bakUnzipOpen").click(function(){
            if(checkERROR(config.get('bakUnzip'))||!config.get('bakUnzip')){
                config.set('bakUnzip',true);
                $("#bakUnzipClose").parent().removeClass("active");
                $("#bakUnzipOpen").parent().addClass("active");
                customAlert("开启备用解压程序","success");
            }
        });
        $("#bakUnzipClose").click(function(){
            if(checkERROR(config.get('bakUnzip'))||config.get('bakUnzip')){
                config.set('bakUnzip',false);
                $("#bakUnzipOpen").parent().removeClass("active");
                $("#bakUnzipClose").parent().addClass("active");
                customAlert("关闭备用解压程序","success");
            }
        });
        $("#setBackground").click(function(){
            chooseFile(function(paths){
                var p=unescape(paths);
                var target="apps/index/css/wotbg.png";
                fs.stat(p,function(err, st){
                    if( st.isFile() ){
                        // 创建读取流
                        var readable = fs.createReadStream( p );
                        // 创建写入流
                        var writable = fs.createWriteStream( target );
                        // 通过管道来传输流
                        readable.pipe( writable );
                        customAlert("修改背景已成功，请刷新页面生效","success");
                    }
                });

            });
        });
        loadGamePatch();
	});
    getPatchList(examPatchList);
}

//检测设置的游戏路径是否合适
function examineStarter(p,callback) {
    console.log("path", p);
    if (p.toLowerCase().indexOf("worldoftanks.exe") == -1 && p.toLowerCase().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(checkVersion()){
            $("#gamever").val(config.get("gameversion"));
        };
        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(baseurl+"dossier\\main.exe",['reg']);
	spawn.stdout.on('data', function (data) {
		examineStarter(data.toString().trim());
	});
	spawn.stderr.on('data', function (data) {
		customAlert("自动设置路径失败，请尝试手动设置路径",'warning');
	});
	//检验是否存在文件
	//不存在则读取录像播放位置
	//检验是否存在
	//不存在则提示用户选择
}
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 "+config.get("gameversion") ;
    }
	$.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))){
        //本地版本小于服务器版本
        var ver1=Number(versionDB.get(patch.name));
        var ver2=Number(patch.version);
        if(ver1<ver2){
            customAlert(patch.name+'有新补丁了，更新内容:<br/>'+patch.description,'warning',1500);
            configPage();
        }
    }
}

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,"\\\\");

    var zip = new AdmZip(file);
    zip.extractAllTo(dir + "\\" ,true);
    var zipEntries = zip.getEntries(); // an array of ZipEntry records
    var list = [];
    callback(file,dir);
}

function checkVersion(){
    if(checkERROR(config.get("path"))){
        getInstallPath();
        return false;
    }
    if(!fs.existsSync(config.get("path")+"\\paths.xml")){
        if(checkERROR(config.get("gameversion"))){
            customAlert(config.get("path")+"\\paths.xml不存在，无法识别游戏版本，请于设置页面手动设置","warning");
            return false;
        }
        else return true;
    }
    var fileData = fs.readFileSync(config.get("path")+"\\paths.xml", "ascii");
    //console.log(fileData);
    var idx=fileData.indexOf('./res_mods/');
    var gamever=fileData.substr(idx+11,fileData.indexOf('<',idx)-11-idx);
    console.log(gamever);
    if(checkERROR(config.get("gameversion"))||config.get("gameversion")!=gamever){
        if(checkERROR(config.get("gameversion"))){
            customAlert("第一次使用沙盘建议先执行  插件管理——清空插件目录\n避免出现插件兼容问题","success");
        }
        config.set("gameversion",gamever);
        customAlert("已识别当前游戏版本为"+gamever,"success");
    }
    return true;
}
function loadGamePatch(){
    //启动更新程序
    var bufs = [];
    if(checkERROR(config.get("path"))){
        return;
    }
    var gamepatch=cp.spawn(baseurl+"dossier\\main.exe",['patch',config.get("path")]);
    gamepatch.stdout.on('data', function (data) {
        bufs.push(data);
    });
    gamepatch.stderr.on('data', function (data) {
    });
    gamepatch.stdout.on('end', function () {
        if(bufs.length>0){
            var buf = Buffer.concat(bufs);
            var patchlist=JSON.parse(buf.toString().replace(/\'/g,'"'));
            for(var i in patchlist['patch']){
                var p=patchlist['patch'][i];
                var tr="<tr>";
                tr+="<td url='"+(patchlist['baseurl']+i).replace('\\\\','\\\\\\\\')+"' class=''>"+i+"</td>";
                tr+="<td class=''>"+p['size']+"</td>";
                if (Number(p['size'])==Number(p['localsize'])){
                    tr+="<td class=''>已下载</td>";
                    tr+="<td><a href='#' class='btn btn-xs btn-info' onclick='customAlert(\""+(patchlist['baseurl']+i).replace('\\\\','\\\\\\\\')+"\",\"info\",20000)'>地址</a></td>";
                }else {
                    tr+="<td class=''>未下载</td>";
                    tr+="<td><a href='#' class='btn btn-xs btn-info' onclick='customAlert(\""+(patchlist['baseurl']+i).replace('\\\\','\\\\\\\\')+"\",\"info\",20000)'>地址</a>&nbsp;<a href='#' class='btn btn-xs btn-danger gamepatchdownload'>下载</a></td>";
                }
                tr+="</tr>";
                $("#gamepatch tbody").append(tr);
            }
            $(".gamepatchdownload").click(function(){
                var url=$(this).parent().siblings().eq(0).attr('url');
                var file=$(this).parent().siblings().eq(0).text();
                downloadCenter.add(url,config.get('path')+"/updates/"+file,file,null,config.get('path')+"/updates/",10);
                $(this).addClass("disabled");
            });
            $("#gamepatch").show();
        }else{
            $("#gamepatch").hide();
        }
    });
}

function checkDir(){
    return;
}