/**
 * Created by adri1 on 2015/12/23.
 */
function updateReplay(){
    var replaydb = new Config("replay.db");
    var replaylist = listFolderRecursive(config.get("path")+"/replays/");
    var update=false;
    for(var i in replaylist){
        if(replaylist[i] in replaydb.json){
            continue;   //跳过已知录像
        }
        if(replaylist[i].indexOf("wowsreplay")==-1){
            continue;
        }
        var fileData = fs.readFileSync(replaylist[i], "ascii");
        var idx1=fileData.indexOf('{"clientVersionFromXml"');
        var idx2=fileData.indexOf("}",fileData.indexOf('"playerVehicle"'));
        if(idx1==-1||idx2==-1){
            continue;
        }
        var data=JSON.parse(fileData.substring(idx1,idx2+1));
        replaydb.set(replaylist[i],{
            time:data['dateTime'],
            map:data['mapName'],
            mode:data['gameLogic'],
            vehicle:data['playerVehicle'],
            version:data['clientVersionFromExe'],
            type:data['matchGroup']
        });
        update=true;
    }
    var delList=[];
    for(var path in replaydb.json){
        if(!fs.existsSync(path)){
            delList.push(path);
        }
    }
    for(var i in delList){
        replaydb.remove(delList[i]);
        update=true;
    }
    return update;
}

function showReplays(){
    if (checkERROR(config.get("path"))){
        customAlert("未找到游戏路径，请先在沙盘设置中指定","danger","5000");
        return;
    }
    if (!checkReplay()){
        customAlert("未开启录像功能，请先在沙盘设置中开启","warning","5000");
    }
    updateReplay();
    $("#replaypage").load("replay.html #replaytable",function(data){
        var replaydb = new Config("replay.db");
        for(var file in replaydb.json){
            var replay=replaydb.json[file];
            var tr="<tr file='"+toPath(file)+"'>";
            var d=replay['time'].split(" ");
            var d1=d[0].split(".");
            tr+="<td>"+d1[2]+"-"+d1[1]+"-"+d1[0]+" "+d[1]+"</td>";
            var version=replay['version'].split(",");
            tr+="<td>"+version[0].trim()+"."+version[1].trim()+"."+version[2].trim()+"</td>";
            var ship=getShipById(replay['vehicle'].split("-")[0]);
            var shipname="";
            var shiptype="";
            var shiplvl=0;
            var shipid=0;
            if(checkERROR(ship)){
                shipname="未知";
                shiptype="未知";
            }else{
                shipname=ship['alias'];
                shiplvl=ship['lvl'];
                shiptype=getTypeName(ship['type']);
                shipid=ship['id']
            }
            tr+="<td>"+shiplvl+"</td>";
            tr+="<td>"+shiptype+"</td>";

            tr+="<td><img class='shippng' src='../../../gameres/gui/ship_icons/"+shipid+".png'><span class=''>"+shipname+"</span></td>";
            tr+="<td onmousemove='showImage(\"../../../gameres/"+replay['map']+"/minimap.png\",\"\")' onmouseout='hideImage()'><img class='mappng' src='../../../gameres/"+replay['map']+"/screen.png'><span class='mapname'>"+getMapName(replay['map'].replace("spaces/","").toUpperCase())+"</span></td>";
            tr+="<td>"+getGameType(replay['type'])+"</td>";
            tr+="<td>"+getGameMode(replay['mode'])+"</td>";
            tr+="<td><button class='replayOpen btn btn-success'>打开</button>&nbsp;&nbsp;<button class='replayDelete btn btn-danger'>删除</button></td>";
            tr+="</tr>";
            $("#replaybody").append(tr);
        }
        $(".replayOpen").click(function(){
            var file=$(this).parent().parent().attr("file");
            cp.spawn(config.get('path')+"\\WorldOfWarships.exe",[file]);
        });
        $(".replayDelete").click(function(){
            var tr=$(this).parent().parent();
            var file=$(this).parent().parent().attr("file");
            customConfirm("确认要删除录像?",function(){
                delFile(file.replace(/\//g, "\\"));
                tr.remove();
            });
        });
        $("#pngrepair").click(function(){
            $(this).addClass("disabled");
            if(fs.existsSync("apps/exe/wowsunpack.exe")){
                var dl=cp.spawn("apps\\exe\\wowsunpack.exe",['-x','-I','spaces/*/screen.png;gui/ship_icons/*;','-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(){
                    customAlert("录像管理图片修复完成","success");
                });
            }
        });
        if($("#replaybody").children().length>0) {
            $("table#replaytable").tablesorter({
                sortInitialOrder: "desc",
                sortList: [
                    [ 0,1 ]
                ]
            });
        }
    });
    $("#replaypage").show();
}

function getMapName(name){
    if(!checkERROR(mapDict)){
        if(name in mapDict){
            return mapDict[name];
        }
    }
    if(name.indexOf("_")!=-1){
        return name.substr(name.indexOf("_")+1);
    }
    return name;
}

function getGameMode(mode){
    switch(mode.toLowerCase()){
        case "domination":
            return "制海权";
        case "zone":
            return "区域战";
        case "encounter":
            return "夺旗战";
        case "default":
            return "对攻战";
        default:
            return mode;
    }
}

function getGameType(type){
    switch(type.toLowerCase()){
        case "pvp":
            return "PvP";
        case "ranked":
            return "排位战";
        case "pve":
            return "PvE";
        default:
            return type;
    }
}