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>"+server+":"+nick+"</td><td><button type='button' class='btn btn-info chooseAccount'>选择</button><button type='button' class='btn 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);
                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(!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();
				});
			});
		});
        $("#gamever").change(function(){
            $("#customVer").show();
        })
        $("#customVer").click(function(){
            config.set("gameversion",$("#gamever").val());
            customAlert("已设置当前游戏版本为"+config.get("gameversion"),"success");
            $("#customVer").hide();
        });
        $("#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();
        });
        loadGamePatch();
	});
    	getPatchList(examPatchList);
}

//检测设置的游戏路径是否合适
function examineStarter(p,callback) {
    console.log("path", p);
    if (p.toLowerCase().indexOf("worldofwarships.exe") == -1 && p.toLowerCase().indexOf("wowslauncher.exe") == -1) {
        p = p + "\\worldofwarships.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;
}

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 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+9,fileData.indexOf('<',idx)-9-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("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 class=''>"+i+"</td>";
                tr+="<td class=''>"+patchlist['baseurl']+i+"</td>";
                tr+="<td class=''>"+p['size']+"</td>";
                if (Number(p['size'])==Number(p['localsize'])){
                    tr+="<td class=''>已下载</td>";
                    tr+="<td></td>";
                }else {
                    tr+="<td class=''>未下载</td>";
                    tr+="<td><a href='#' class='btn btn-xs btn-default gamepatchdownload'>下载</a></td>";
                }
                tr+="</tr>";
                $("#gamepatch tbody").append(tr);
            }
            $(".gamepatchdownload").click(function(){
                var url=$(this).parent().siblings().eq(1).text();
                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 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>");
}