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.db");

//设置页面
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('account'))){
            var account=config.get('account');
            for(var i in account['list']){
                var active=false;
                if(i==account['active']){
                    active=true;
                }
                var aid=i;
                var nick=account['list'][i]['nick'];
                var server=account['list'][i]['server'];
                if(checkERROR(nick)||checkERROR(server)){
                    continue;
                }
                $("#accountTable").append("<tr class='accountTr "+(active?"active":"")+"' aid='"+aid+"'><td style='line-height: 30px;'>"+server+":"+nick+"</td><td><button type='button' class='btn btn-sm btn-info chooseAccount'>选择</button>&nbsp;&nbsp;&nbsp;<button type='button' class='btn btn-sm btn-danger delAccount'>删除</button></td></tr>")
            }
            $(".chooseAccount").click(function(){
                $(".accountTr.active").removeClass("active");
                $(this).parent().parent().addClass("active");
                var c=config.get('account');
                c['active']=$(this).parent().parent().attr('aid');
                config.set('account',c);

                if(config.get('account')['active']>1500000000&&config.get('account')['active']<1900000000){
                    dossier=new ChinaDossier();
                }else{
                    dossier=new OtherDossier();
                }
                setAccountActive();
            });
            $(".delAccount").click(function(){
                var aid=Number($(this).parent().parent().attr('aid').trim());
                var c=config.get('account');
                if(aid==c['active']){
                    customAlert('请先选择另一个帐号启动监控','danger');
                }else{
                    delete c['list'][aid];
                    $(this).parent().parent().remove();
                    config.set('account',c);
                }
            });
        }
        if(checkERROR(config.get('bakUnzip'))||!config.get('bakUnzip')){
            $("#bakUnzipClose").parent().addClass("active");
        }else{
            $("#bakUnzipOpen").parent().addClass("active");
        }
        if(checkReplay()){
            $("#replayOpen").parent().addClass("active");
            $("#replayClose").parent().removeClass("active");
        }else{
            $("#replayClose").parent().addClass("active");
            $("#replayOpen").parent().removeClass("active");
        }
        if(checkTrain()){
            $("#trainOpen").parent().addClass("active");
            $("#trainClose").parent().removeClass("active");
        }else{
            $("#trainClose").parent().addClass("active");
            $("#trainOpen").parent().removeClass("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'));
                    analyseAccount();
				});
			},true);
		});
        $("#gamever").change(function(){
            $("#customVer").show();
        });
        $("#customVer").click(function(){
            config.set("gameversion",$("#gamever").val());
            customAlert("已设置当前游戏版本为"+config.get("gameversion"),"success");
            $("#customVer").hide();
        });
        $("#replayOpen").click(function(){
            setReplay(true);
            customAlert("录像功能开启","success");
        });
        $("#replayClose").click(function(){
            setReplay(false);
            customAlert("录像功能关闭","success");
        });
        $("#trainOpen").click(function(){
            if(checkERROR(config.get("path"))||!fs.existsSync(config.get("path")+"\\res\\scripts_config.xml")){
                customAlert("未找到用来设置的文件","warning",3000);
                return;
            }
            var fileData = fs.readFileSync(config.get("path")+"\\res\\scripts_config.xml", "utf-8");
            fileData=fileData.replace("<disableTrainingRoom>true</disableTrainingRoom>","<disableTrainingRoom>false</disableTrainingRoom>");
            fs.writeFileSync(config.get("path")+"\\res\\scripts_config.xml", fileData);
            customAlert("训练模式开启，进入游戏后在模式中选择训练即可",'success');
            $("#trainOpen").parent().addClass("active");
            $("#trainClose").parent().removeClass("active");
        });
        $("#trainClose").click(function(){
            customAlert("关闭功能没做，真的有人点啊- -|||",'success');
        });
        $("#setBackground").click(function(){
            chooseFile(function(paths){
                var p=unescape(paths);
                var target="apps/index/wows/css/wowsbg.jpg";
                fs.stat(p,function(err, st){
                    if( st.isFile() ){
                        // 创建读取流
                        var readable = fs.createReadStream( p );
                        // 创建写入流
                        var writable = fs.createWriteStream( target );
                        // 通过管道来传输流
                        readable.pipe( writable );
                        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");
            }
        });
        $("#refreshAccount").click(function(){
            analyseAccount();
        });
        $("#pathsRepair").click(function(){
            pathsXmlCheck();
        });
        loadGamePatch();
	});
    	getPatchList(examPatchList);
}

//检测设置的游戏路径是否合适
function examineStarter(p,callback) {
    console.log("path", p);
    var p=findFolderRecursive(p,"worldofwarships.exe",0);
    if (!checkERROR(p)&&p!="") {
        p = toPath(p.substr(0, p.lastIndexOf("/")));
        config.set('path',p);
        customAlert("游戏路径修改为:" + p, 'success');
        if(checkVersion()){
            $("#gamever").val(config.get("gameversion"));
        }
        if (typeof(callback) == "function") {
            callback();
        }
    }
    else {
        customAlert("设置路径失败，找不到游戏启动程序", 'warning');
    }
}

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('战舰模块');
    }
	$.get("http://rank.kongzhong.com/ModDownload/action/PatchAction/wowspatchList", 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',10000);
            configPage();
        }
    }else{
        customAlert(patch.name+'有新补丁了，更新内容:<br/>'+patch.description,'warning',10000);
        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) {
        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 checkReplay(){
    if(checkERROR(config.get("path"))||!fs.existsSync(config.get("path")+"\\preferences.xml")){
        $("#replayOpen").addClass("disabled");
        $("#replayClose").addClass("disabled");
        return;
    }
    $("#replayOpen").removeClass("disabled");
    $("#replayClose").removeClass("disabled");
    var fileData = fs.readFileSync(config.get("path")+"\\preferences.xml", "ascii");
    if(fileData.indexOf("<isReplayEnabled>")==-1||fileData.indexOf("<ReplayCameraUpdate>")==-1){
        return false;
    }else{
        return true;
    }
}
function checkTrain(){
    if(checkERROR(config.get("path"))||!fs.existsSync(config.get("path")+"\\res\\scripts_config.xml")){
        return false;
    }
    var fileData = fs.readFileSync(config.get("path")+"\\res\\scripts_config.xml", "ascii");
    if(fileData.indexOf("<disableTrainingRoom>true</disableTrainingRoom>")!=-1){
        return false;
    }else{
        return true;
    }
}

function setReplay(open){
    if(checkERROR(config.get("path"))||!fs.existsSync(config.get("path")+"\\preferences.xml")){
        customAlert("未找到用来设置的文件","warning",3000);
        return;
    }
    var fileData = fs.readFileSync(config.get("path")+"\\preferences.xml", "ascii");
    if(open){
        fileData=fileData.replace("</scriptsPreferences>","<isReplayEnabled>	true	</isReplayEnabled><ReplayCameraUpdate>	30	</ReplayCameraUpdate></scriptsPreferences>");
        $("#replayOpen").parent().addClass("active");
        $("#replayClose").parent().removeClass("active");
    }else{
        var idx1=fileData.indexOf("<isReplayEnabled>");
        var idx2=fileData.indexOf("</isReplayEnabled>")+18;
        fileData=fileData.replace(fileData.substring(idx1,idx2),"");
        idx1=fileData.indexOf("<ReplayCameraUpdate>");
        idx2=fileData.indexOf("</ReplayCameraUpdate>")+21;
        fileData=fileData.replace(fileData.substring(idx1,idx2),"");
        $("#replayClose").parent().addClass("active");
        $("#replayOpen").parent().removeClass("active");
    }
    fs.writeFileSync(config.get("path")+"\\preferences.xml", fileData);
}
function checkVersion(ask){
    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/');
    if(idx==-1){
        customAlert("无法识别版本，paths.xml被破坏","danger");
        return false;
    }
    var gamever=fileData.substr(idx+9,fileData.indexOf('<',idx)-9-idx);
    //console.log(gamever);
    if(!checkERROR(ask)&&ask&&config.get("gameversion")!=gamever){
        customConfirm("检测到当前游戏版本为"+gamever+"，是否更新版本设定使插件安装到正确位置?",function(){
            config.set("gameversion",gamever);
        });
    }
    else 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("apps\\dossier\\analyse.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 analyseAccount(){
    if(checkERROR(config.get('path'))){
        customAlert('请先指定游戏路径','danger');
    }else{
        var p=config.get('path');
        p+="\\profile\\python.log";
        if(!fs.existsSync(p)){
            customAlert('未找到可扫描的帐号文件，请先登录游戏','warning');
            return;
        }
        customAlert('扫描帐号文件','info');
        var es = cp.spawn("apps/dossier/analyse.exe", ['account',p]);
        var bufs = [];
        es.stdout.on('data', function (data) {
            bufs.push(repairCharset(data));
        });
        es.stderr.on('data', function (data) {
            customAlert("错误:" + repairCharset(data), 'danger');
        });
        es.stdout.on('end', function () {
            var buf = Buffer.concat(bufs);
            var output = buf.toString();
            var accounts=output.split("\n");
            var c=config.get('account');
            if(checkERROR(c)){
                c={'active':0,'list':{}};
            }
            for(var i in accounts){
                var a=accounts[i];
                if(a.length==0){
                    continue;
                }
                var acc=a.split(" ");
                if(acc[0].trim().length==0){
                    continue;
                }
                c['list'][acc[0]]={
                    'nick':acc[1].trim(),
                    'server':acc[2].trim()
                }
            }
            config.set('account',c);
            customAlert("扫描完毕",'success');
            checkNowPage("",true);
            refreshConfig();
        });
    }
}

function pathsXmlCheck(){
    if(checkERROR(config.get('path'))){
        customAlert('请先指定游戏路径','danger');
        return;
    }
    $(this).addClass("disabled");
    if(fs.existsSync("apps/exe/wowsunpack.exe")){
        var dl=cp.spawn("apps\\exe\\wowsunpack.exe",['-x','-I','scripts/entity_defs/Account.def;','-o','gameres',config.get("path")+'\\res_packages']);
        dl.stdout.on('data', function (data) {
            console.log(data);
        });
        dl.stderr.on('data', function (data) {
            console.log(data);
        });
        dl.on('exit',function(){
            var version='';
            var path="gameres\\scripts\\entity_defs\\Account.def";
            var def=fs.readFileSync(path,"ascii");
            var idx1=def.indexOf("curVersion_Release");
            var idx2=def.indexOf(">",idx1);
            var key=def.substring(idx1,idx2);
            var keys=key.split("_");
            if(keys.length==7){
                version=keys[2]+"."+keys[3]+"."+keys[4]+"."+keys[5];
            }else if(keys.length==8&&keys[2].toLowerCase()=="cn"){
                version=keys[3]+"."+keys[4]+"."+keys[5]+"."+keys[6];
            }else{
                customAlert("检测失败，代码:"+key,"danger");
                return;
            }

            var xml=fs.readFileSync(config.get("path")+"\\paths.xml", "ascii");
            var idx1=xml.indexOf("<Paths>");
            var idx2=xml.lastIndexOf("</Paths>");
            var main=xml.substring(idx1+7,idx2);
            var paths=main.split("</Path>");
            var xmlCheck=paths.length==5;
            for(var p in paths){
                p = p.trim();
            }
            if(xmlCheck){
                xmlCheck=(paths[0].substr(paths[0].lastIndexOf(">"))==">profile"&&paths[1].substr(paths[1].lastIndexOf(">"))==(">res_mods/"+version)&&paths[2].substr(paths[2].lastIndexOf(">"))==">res_packages"&&paths[3].substr(paths[3].lastIndexOf(">"))==">res");
            }
            if(xmlCheck){
                customAlert("检测无异常","success");
            }else{
                customConfirm("检测到异常，是否修复?",function(){
                    var content="<root>\n\t<Paths>\n\t\t<Path>profile</Path>\n\t\t<Path>res_mods/"+version+"</Path>\n\t\t<Path>res_packages</Path>\n\t\t<Path>res</Path>\n\t</Paths>\n</root>";
                    fs.writeFileSync(config.get("path")+"\\paths.xml",content);
                    customAlert("修复完成","success");
                });
            }
        });
    }
}

function getServerName(aid){
    if(aid>2000000000){
        return '亚服';
    }
    if(aid>1000000000){
        return '美服';
    }
    if (aid>500000000) {
        return '欧服';
    }
    if(aid>7000000){
        return '俄服'
    }
    return '未知';
}
function getServerURL(aid){
    if(aid>2000000000){
        return 'http://worldofwarships.asia/zh-tw/community/accounts/'+aid+'-a/';
    }
    if(aid>1500000000){
        return 'http://rank.kongzhong.com/wows/index.html?aid='+aid;
    }
    if(aid>1000000000){
        return 'http://worldofwarships.com/en/community/accounts/'+aid+'-a/';
    }
    if (aid>500000000) {
        return 'http://worldofwarships.eu/en/community/accounts/'+aid+'-a/';
    }
    if(aid>7000000){
        return 'http://worldofwarships.ru/ru/community/accounts/'+aid+'-a/';
    }
    return '';
}

function setAccountActive(){
    if(checkERROR(config.get('account'))||checkERROR(config.get('account')['active'])){
        return;
    }
    var aid=config.get('account')['active'];
    var account=config.get('account')['list'][aid];
    $("#user").html("<a target='_blank' href='"+getServerURL(aid)+"'>"+account['server']+" : "+account['nick']+"</a>");
}