/**
 * Created by adri1 on 2015/9/1.
 */
var PaintManager=function(){
    this.db =  new Config("paint.db");
}
PaintManager.prototype={
    install:function(id){
        var url="http://rank.kongzhong.com/ModDownload/action/ModelAction/download?modelid="+id;
        var model=this.modeljson[id];
        var type="";
        if(model.sort=="paint"){
            type="涂装";
        }else if (model.sort=="model"){
            type="模型"
        }
        var savepath = "download_mods/[model]" + model.name+model.ext;
        var pm=this;
        downloadCenter.add(url, savepath, model.name, function (paths) {
            var id=getUniqueId();
            pm.newRecord(paths, model.id, model['updatetime']['time']);
            pm.downloadXML(model.id);
        });
    },
    downloadXML:function(id){
        var pm=this;
        var model=this.modeljson[id];
        //存在可选的配置文件
        if(model['xml']!="") {
            var url = model['xml'];
            var savepath = "download_mods/[model]" + model['name'] + "xml" + url.substr(url.lastIndexOf('.'));
            downloadCenter.add(url, savepath, model['name'] + "配置文件", function (paths) {
                pm.installXML(id);
            });
        }else{
            var uid=getUniqueId();
            new CleverInstaller(uid, model.name, paintManager.db.get(id)['file'], "install",false);
        }
    },
    installXML:function(id){
        var uid=getUniqueId();
        var model=this.modeljson[id];
        var savepath = "download_mods/[model]" + model['name'] + "xml" + model['xml'].substr(model['xml'].lastIndexOf('.'));
        //存在可选的配置文件
        var tip=new Tips(uid);
        tip.init(model['name'] + '配置文件', '开始准备内容<br/>');
        unCompress(savepath,uid,function(zipfilelist){
            //遍历配置包检查可选覆盖车辆
            tip.remove();
            var xmlList={};
            for (var i in zipfilelist) {
                try {
                    var xml = zipfilelist[i];
                    xml = xml.replace(/\//g, "\\");
                    if (xml.lastIndexOf(".") == -1) {
                        continue;
                    }
                    if (xml.indexOf("vehicles") != -1) {
                        var p = xml.substr(xml.indexOf("vehicles"));
                        xml = p.split("\\")[2];
                    }
                    var start = xml.lastIndexOf("\\");
                    if (start == -1) {
                        start = 0;
                    }
                    xmlList[xml.substr(start, xml.lastIndexOf(".")).toLowerCase()] = 1;
                } catch (e) {
                    continue;
                }
            }
            //遍历插件包检查默认覆盖车辆
            analyseTankid(paintManager.db.get(id)['file'],function(mainlist){

                var defaultlist="";     //默认必选
                var extralist="";       //配置可选
                //识别可选坦克
                for(var i in tanksjson){
                    if(model['vid']!="0"){ //全支持型
                        if(tanksjson[i]['name'].toLowerCase() in xmlList){
                            extralist+=getTankLabel(tanksjson[i],'label-md " value="'+i);
                        }
                    }
                    if(tanksjson[i]['modelname'].toLowerCase() in mainlist){
                        defaultlist+=""+getTankLabel(tanksjson[i],'label-md " value="'+i);
                    }
                }


                var div='<div class="modal fade paintModal" id="paintModal'+id+'" tabindex="-1" role="dialog"><div class="modal-dialog modal-lg">';
                div+='<div class="modal-content">';
                div+='<div class="modal-header">';
                div+='<h4 class="modal-title">选择涂装模型生效车辆</h4><small style="color:red;">(可选生效车型可能和炮声插件冲突)</small></div>';
                div+='<div class="modal-body">';
                div+="<div>默认生效车辆</div>";
                div+="<div class='defaultselect'>"+(defaultlist.length>0?defaultlist:"无默认生效对象")+"</div>";
                div+="<div>可选生效车型<small>(点击图标选择)</small></div>";

                //显示选择确认框
                if(model['vid']=="0"){
                    div+="<div>等级: <select class='levelselect form-control'><option value='all'>ALL</option><option value='1'>1级</option><option value='2'>2级</option><option value='3'>3级</option><option value='4'>4级</option><option value='5'>5级</option><option value='6'>6级</option><option value='7'>7级</option><option value='8'>8级</option><option value='9'>9级</option><option value='10'>10级</option></select></div>";
                    div+="<div>类型: <select class='typeselect form-control'><option value='all'>ALL</option><option value='lightTank'>轻型坦克</option><option value='mediumTank'>中型坦克</option><option value='heavyTank'>重型坦克</option><option value='AT-SPG'>自行反坦克炮</option><option value='SPG'>自行火炮</option></select></div>";
                    div+="<div>国家: <select class='countryselect form-control'><option value='all'>ALL</option><option value='china'>中国</option><option value='usa'>美国</option><option value='ussr'>苏联</option><option value='germany'>德国</option><option value='france'>法国</option><option value='uk'>英国</option><option value='japan'>日本</option><option value='czech'>捷克</option></select></div>";
                    div+="<div><button class='btn btn-primary showTanks'>显示车辆</button></div><div class='extraselect'></div>";
                }else{
                    div+="<div class='extraselect'>"+extralist+"</div>";
                }
                div+='</div>';
                div+='<div class="modal-footer">';
                div+='<button type="button" class="btn btn-default" data-dismiss="modal" id="paintInstall">安装到指定车辆</button>';
                div+='<button type="button" class="btn btn-primary" data-dismiss="modal" id="cancelPaintInstall">取消安装</button>';
                div+='</div>';
                div+='</div></div></div>';
                $("#paint").append(div);
                $('#paintModal'+id).modal({ backdrop:"static" });
                $(".extraselect .label").click(function(){
                    $(this).toggleClass("active");
                });
                $(".showTanks").click(function(){
                    $(".extraselect .label:not(.active)").remove();
                    var level=$(".levelselect").val();
                    var type=$(".typeselect").val();
                    var country=$(".countryselect").val();
                    for(var i in tanksjson){
                        var tank=tanksjson[i];
                        if((level=='all'||level==tank['level'])&&(type=='all'||type==tank['entype'])&&(country=='all'||country==tank['encountry'])){
                            $(".extraselect").append(getTankLabel(tank,'label-md " value="'+i));
                        }
                    }
                    $(".extraselect .label").click(function(){
                        $(this).toggleClass("active");
                    });
                });
                $("#paintInstall").click(function(){
                    //安装基本包
                    new CleverInstaller(uid, model.name, paintManager.db.get(id)['file'], "install",false);
                    //复制选择的配置
                    var selectList=[];
                    $(".label.active").each(function(){
                        selectList.push($(this).attr('value').trim());
                    });
                    var cp=new CopyManager(uid, model['name'] + '配置文件安装', true, null,function(){
                    });
                    for(var i in zipfilelist){
                        var xml = zipfilelist[i];
                        xml = xml.replace(/\//g, "\\");
                        if (xml.lastIndexOf(".") == -1) {
                            continue;
                        }
                        var selected=0;
                        for(var j in selectList){
                            if(xml.toLowerCase().indexOf(tanksjson[selectList[j]]['name'].toLowerCase())!=-1){
                                selected=selectList[j];
                                break;
                            }
                        }
                        if(selected!=0){
                            //针对选择的车辆将文件覆盖到指定位置。
                            cp.add(cleverInstallDirname + "/" + uid+"/"+xml.trim(),config.get("path")+"/res_mods/"+config.get("gameversion")+"/scripts/item_defs/vehicles/"+(tanksjson[selected]['encountry'])+"/"+tanksjson[selected]['name']+".xml");
                        }
                    }
                    cp.start();
                });
            });
        });
    },
    newRecord:function(file,id,time){
        this.db.set(id,{
            "updatetime":time,
            "file":file
        })
    },
    loadRemoteList:function(callback){
        if(checkERROR(this.modeljson)){
            var pm=this;
            $.get("http://rank.kongzhong.com/ModDownload/action/ModelAction/modelList", function(data, status) {
                pm.modeljson = data;
                pm.checkFileList();
                pm.checkModelInstalled();
                pm.checkUpdate();
                if (typeof(callback) == "function") {
                    callback();
                }
            });
        }else{
            if (typeof(callback) == "function") {
                callback();
            }
        }
    },
    checkFileList:function(){
        for(var i in this.db.json){
            if(fs.existsSync("download_mods/"+this.db.json[i]['file'])){
                this.db.json[i]['fileExist']=true;
            }else{
                this.db.json[i]['fileExist']=false;
            }
        }
    },
    checkUpdate:function(){
        for(var i in this.db.json){
            if(this.db.json[i]['updatetime']<this.modeljson[i]['updatetime']['time']){
                this.db.json[i]['update']=true;
            }else{
                this.db.json[i]['update']=false;
            }
        }
    },
    checkModelInstalled:function(){
        if(checkERROR(config.get('gameversion'))||checkERROR(config.get('path'))){
            return;
        }
        this.tankInstalled={};
        var resultList={};
        var xmllist=listFolderRecursive(config.get('path')+"/res_mods/"+config.get('gameversion')+'/scripts/item_defs/vehicles');
        for (var i in xmllist){
            try {
                var xml=xmllist[i];
                var p=xml.substr(xml.indexOf("vehicles"));
                var name= p.split("/")[2];
                resultList[name.substr(0,name.lastIndexOf(".")).toLowerCase()]=0;
            }catch(e){
                continue;
            }
        }
        var modellist=listFolderRecursive(config.get('path')+"/res_mods/"+config.get('gameversion')+'/vehicles');
        for(var i in modellist){
            try {
                var model = modellist[i];
                var p = model.substr(model.indexOf("vehicles"));
                var name = p.split("/")[2];
                resultList[name.toLowerCase()] = 1;
            }catch(e){
                continue;
            }
        }
        for(var i in tanksjson){
            if(tanksjson[i]['name'].toLowerCase() in resultList){
                this.tankInstalled[i]=resultList[tanksjson[i]['name'].toLowerCase()];
            }else if(tanksjson[i]['modelname'].toLowerCase() in resultList){
                this.tankInstalled[i]=resultList[tanksjson[i]['modelname'].toLowerCase()];
            }
        }
    }
}
var paintManager=new PaintManager();

function modelInstall(id){
    paintManager.install(id);
}
function modelReInstall(id){
    paintManager.downloadXML(id);
}
function refreshPaintList(){
    checkNowPage("paintlist",true);
    if ($("#modlist").html().length > 0) {
        $("#modlist").html("");
    }
    $("#modlist").load("paintlist.html #paint", function (data) {
        paintManager.loadRemoteList(showPaintList);
        $("#paintremove").click(function(){
            paintManager.checkModelInstalled();
            var div='<div class="modal fade paintModal" id="modelremove" tabindex="-1" role="dialog"><div class="modal-dialog modal-lg">';
            div+='<div class="modal-content">';
            div+='<div class="modal-header">';
            div+='<h4 class="modal-title">已发现以下安装内容</h4></div>';
            div+='<div class="modal-body">';
            div+="<div>默认生效车型</div>";
            div+="<div class='defaultselect'>";
            for(var i in paintManager.tankInstalled){
                if(paintManager.tankInstalled[i]==1){
                    div+=getTankLabel(tanksjson[i],'label-md " value="'+i);
                }
            }
            div+="</div>";
            div+="<div>配置文件生效车型</div>";
            var extralist="";
            var size=0;
            for(var i in paintManager.tankInstalled){
                if(paintManager.tankInstalled[i]==0){
                    size++;
                    extralist+=getTankLabel(tanksjson[i],'label-md " value="'+i)+"&nbsp;";
                }
            }
            //显示选择确认框
            if(size>100){
                div+="<div style='color:red;'>发现大量涂装配置，由于和炮声配置文件冲突，请谨慎选择卸载</div>"
                div+="<div>等级: <select class='levelselect form-control'><option value='all'>ALL</option><option value='1'>1级</option><option value='2'>2级</option><option value='3'>3级</option><option value='4'>4级</option><option value='5'>5级</option><option value='6'>6级</option><option value='7'>7级</option><option value='8'>8级</option><option value='9'>9级</option><option value='10'>10级</option></select></div>";
                div+="<div>类型: <select class='typeselect form-control'><option value='all'>ALL</option><option value='lightTank'>轻型坦克</option><option value='mediumTank'>中型坦克</option><option value='heavyTank'>重型坦克</option><option value='AT-SPG'>自行反坦克炮</option><option value='SPG'>自行火炮</option></select></div>";
                div+="<div>国家: <select class='countryselect form-control'><option value='all'>ALL</option><option value='china'>中国</option><option value='usa'>美国</option><option value='ussr'>苏联</option><option value='germany'>德国</option><option value='france'>法国</option><option value='uk'>英国</option><option value='japan'>日本</option><option value='czech'>捷克</option></select></div>";
                div+="<div><button class='btn btn-primary showTanksInstall'>显示车辆</button></div><div class='extraselect installFilter'>"+extralist+"</div>";
            }else if(size==0){
                div+="<div class='extraselect'>无可卸载的配置文件</div>";
            }else{
                div+="<div class='extraselect'>"+extralist+"</div>";
            }
            div+="<div>选择预删除的车辆图标</div>";
            div+='</div>';
            div+='<div class="modal-footer">';
            div+='<button type="button" class="btn btn-danger" data-dismiss="modal" id="paintUninstall">卸载指定车辆涂装</button>';
            div+='</div>';
            div+='</div></div></div>';
            if($("#modelremove")){
                $("#modelremove").remove();
            }
            $("#paint").append(div);
            $("#modelremove").modal();
            $("#modelremove .label").click(function(){
                $(this).toggleClass("active");
            });
            $(".showTanksInstall").click(function(){
                var level=$("#modelremove .levelselect").val();
                var type=$("#modelremove .typeselect").val();
                var country=$("#modelremove .countryselect").val();
                $(".extraselect .label:not(.active)").each(function(){
                    var id=$(this).attr("value").trim();
                    var tank=tanksjson[id];
                    if(checkERROR(tank)){
                        return;
                    }
                    if((level=='all'||level==tank['level'])&&(type=='all'||type==tank['entype'])&&(country=='all'||country==tank['encountry'])){
                        $(this).show();
                    }else{
                        $(this).hide();
                    }
                });
            });
            $("#paintUninstall").click(function(){
                var labels="";
                $("#modelremove .label.active").each(function(){
                    labels+=getTankLabel(tanksjson[$(this).attr("value").trim()]);
                });
                customConfirm("<div>确认要卸载以下车辆的涂装模型:</div><div>"+labels+"</div>",function(){
                    var deletepaths=[];
                    var basepath=config.get("path");
                    var ver=config.get("gameversion");
                    $("#modelremove .label.active").each(function(){
                        var id=$(this).attr("value").trim();
                        var tank=tanksjson[id];
                        if(checkERROR(tank)){
                            return;
                        }
                        var path="";
                        if(paintManager.tankInstalled[id]==0){
                            path=basepath+"/res_mods/"+ver+"/scripts/item_defs/vehicles/"+(tank['encountry'])+"/"+tank['name']+".xml";
                        }else if(paintManager.tankInstalled[id]==1){
                            path=basepath+"/res_mods/"+ver+"/vehicles/"+getPatinCountry(tank['encountry'])+"/"+tank['modelname']+"/";
                        }
                        if(fs.existsSync(path)){
                            deletepaths.push(path);
                        }
                    });
                    var dm=new DeleteManager(getUniqueId(),"涂装模型卸载",false,null,null);
                    dm.dir=true;
                    for(var i  in deletepaths){
                        dm.add(deletepaths[i],deletepaths[i]);
                    }
                    dm.start();
                });
            });
        })
    });
}

function showPaintList(){
    try {
        var themedict={};
        var extradict={};
        var vehicledict={};
        var authordict={};
        var typedict={};
        $("#paint").css("height",window.innerHeight-145);
        for(var i in paintManager.modeljson){
            var m=paintManager.modeljson[i];
            addFooter(m);
            if(m.theme!=""){
                putDict(themedict,m.theme);
            }
            putDict(typedict,m.sort);
            if(m['extra']!=""){
                var extra=m['extra'].split("#");
                for(var j in extra){
                    putDict(extradict,extra[j]);
                }
            }
            if(m['vid']!=""&&m['vid']!="0"){
                var vehs=m['vid'].split(",");
                for(var j in vehs){
                    putDict(vehicledict,vehs[j]);
                }
            }
            if(m['author']!=""){
                var author=m['author'].split(",");
                for(var j in author){
                    putDict(authordict,author[j]);
                }
            }
        }
        for(var i in typedict){
            $("#type"+i).find(".badge:first").text(typedict[i]);
        }
        for(var i in themedict){
            $("#theme").append('<button type="button" for="theme" target="theme" value="'+i+'" class="btn btn-sm filterbtn btn-primary">'+i+'&nbsp;<span class="badge">'+themedict[i]+'</span></button>');
        }
        for(var i in extradict){
            $("#extra").append('<button type="button" for="extra" target="extra" value="'+i+'" class="btn btn-sm filterbtn btn-warning">'+i+'&nbsp;<span class="badge">'+extradict[i]+'</span></button>');
        }
        for(var i in authordict){
            $("#author").append('<button type="button" for="author" target="author" value="'+i+'" class="btn btn-sm filterbtn btn-info">'+i+'&nbsp;<span class="badge">'+authordict[i]+'</span></button>');
        }
        for(var i in vehicledict){
            var tank=tanksjson[i];
            if(tank==undefined){
                continue;
            }
            $("#tank").append('<button type="button" level="'+tank['level']+'" entype="'+tank['entype']+'" country="'+tank['encountry']+'" for="tank" target="vid" value="'+i+'" class="btn btn-sm filterbtn label-'+tank['entype']+'">'+tank['alias']+'&nbsp;<span class="badge">'+vehicledict[i]+'</span></button>');
        }
        $("img.lazy").lazyload({ container: $("#footer") });
        $(".footmodel").click(function(){
            var id=$(this).attr("id").substr(5);
            $(this).addClass("active").siblings().removeClass("active");
            selectModel(id);
        });
        var len=$(".footmodel").length;
        var ran=Math.floor(Math.random()*len);
        $(".footmodel:eq("+ran+")").click();

        $("#filter").mousemove(function(){
            $("#copy button").each(function(){
                $("#filterBy").append($(this));
            });
            $("#selectButton").show();
            $("#titlelist").show();
            $("#myTabContent").show();
            $("#copy").hide();
        });
        $("#filter").mouseout(function(){
            $("#selectButton").hide();
            $("#filterBy button").each(function(){
                $("#copy").append($(this));
            });
            if($("#copy").children(".filterbtn").length>0){
                $("#copy").find(".help").remove();
            }else{
                if($("#copy").find(".help").length==0){
                    $("#copy").append('<span class="btn help">涂装筛选</span>');
                }
            }
            $("#titlelist").hide();
            $("#myTabContent").hide();
            $("#copy").show();
        });

        $(".filterbtn").click(function(){
            if($(this).parent().attr("id")=="filterBy"){
                $("#"+$(this).attr("for")).append($(this));
            }else{
                $("#filterBy").append($(this));
            }
            refreshPaintFilter();
        });
        $("#tank input").click(function(){
            $(this).parent().addClass("active").siblings().removeClass("active");
            refreshTankButton();
        });
        $("#filter").mouseout();
    } catch (e) {
        console.log(e);
    }
}

function refreshPaintFilter(){
    if($("#filterBy button").length>0){
        $(".footmodel").each(function(){
            var mid=$(this).attr("id").substring(5);
            var model=paintManager.modeljson[mid];
            var boolDict={};
            $("#filterBy button").each(function(){
                var target=$(this).attr("target");
                var res=false
                if(target=="vid"){
                    if(model[target]=="0"||model[target]==$(this).attr("value")){
                        res=true;
                    }
                }else{
                    res=(model[target].indexOf($(this).attr("value"))!=-1);
                }
                if(target in boolDict){
                    boolDict[target]=boolDict[target]||res;
                }else{
                    boolDict[target]=res;
                }
            });
            var res=true;
            for (var i in boolDict){
                res=res&&boolDict[i];
            }
            if(res){
                $(this).show();
            }else{
                $(this).hide();
            }
        });
    }else{
        $(".footmodel").show();
    }
}
function refreshTankButton(){
    var type="";
    var country="";
    var level="";
    $("input:checked").each(function(){
        if($(this).attr("name")=="levelFilter"){
            level=$(this).val();
        }else if($(this).attr("name")=="typeFilter"){
            type=$(this).val();
        }else if($(this).attr("name")=="countryFilter"){
            country=$(this).val();
        }
    });
    $("#tank button").each(function(){
        if(($(this).attr("level")==level||level=="all")&&($(this).attr("entype")==type||type=="all")&&($(this).attr("country")==country||country=="all")){
            $(this).show();
        }else{
            $(this).hide();
        }
    });
}
function putDict(dict,value){
    if(value in dict){
        dict[value]++;
    }else{
        dict[value]=1;
    }
}
function selectModel(mid){
    var model=paintManager.modeljson[mid];
    var base="<div>";
    base+="<h4 id='dispname' title='"+model.name+"'>"+model.name+"</h4>";
    base+="<p>作者:</p><h4>"+model.author+"</h4>";
    base+="<p>类型:</p><h4>"+(model.sort=="paint"?"涂装":"模型")+"</h4>";
    base+="<p>支持车型:</p>";
    if(model.vid=="0"){
        base+='<span class="label" style="background-color:orange;">全车型</span>';
    }else{
        var vs=model.vid.split(",");
        for(var i in vs){
            var tank=tanksjson[vs[i]];
            base+=getTankLabel(tank);
        }
    }
    if(model.theme!=""){
        base+="<p>主题:</p><h4>"+model.theme+"</h4>";
    }
    base+="<p>下载量:</p><h4>"+model.down+"</h4>";
    base+="<button class='btn btn-default' style='position: absolute;bottom: 10px;left: 15px;' onclick='modelInstall("+model.id+")'>下载</button>";
    if(!checkERROR(paintManager.db.get(model.id))){
        if(paintManager.db.get(model.id)['updatetime']<paintManager.modeljson[model.id]['updatetime']['time']){
            base += "<button class='btn btn-success' style='position: absolute;bottom: 10px;left: 90px;' onclick='modelInstall(" + model.id + ")'>更新</button>";
        }else {
            base += "<button class='btn btn-info' style='position: absolute;bottom: 10px;left: 90px;' onclick='modelReInstall(" + model.id + ")'>重安装</button>";
        }
    }
    base+="</div>";
    $("#base").html(base);
    $("#preview").html("");
    $("#description").html(model.description);
    var imgs=model.image.split(";");
    for(var i in imgs){
        var img=imgs[i];
        if(img.length>0) {
            var pre = "<div class='prev'><img src='" + img + "'></div>";
            $("#preview").append(pre);
        }
    }
    $(".prev").mousemove(function(){
        if($("#imgpreview").html()!=$(this).html()){
            var img=$(this).html();
            $("#imgpreview").fadeOut(200,function(){
                $("#imgpreview").html(img);
                $("#imgpreview").fadeIn(200);
            });
        }
    });
    $(".prev").mouseout(function(){
        $(this).addClass("active").siblings().removeClass("active");
    });
    $
    $(".prev:first").mousemove();
    $(".prev:first").mouseout();
}
function addFooter(model){
    try{
        var div="<div id='model"+model.id+"' class='footmodel'>";
        div+="<div class='modelimage'><img class='lazy' data-original='"+model["image"].split(";")[0]+"'></div>"
        div+="<div class='modelname'>"+model.name+"</div>";
        div+="</div>";
        $("#footer").prepend(div);
    }catch(e){
        console.log(e);
        return;
    }
}
function getTankLabel(tank,style){
    if(checkERROR(style)){
        style="";
    }
    if(checkERROR(tank)){
        return '';
    }else{
        return '<span class="label label-'+tank.entype+' '+style+'">'+tank.alias+'</span>';
    }
}

function analyseTankid(file,callback){
    if(fs.existsSync(file)) {
        listCompress(file, function (list) {
            var resultlist = {};
            for (var i in list) {
                var file = list[i].trim().replace(/\\/g, "/");

                var p = file.substr(file.indexOf("vehicles"));
                var ps=p.split("/");
                if(ps.length<3){
                    continue;
                }
                var name = p.split("/")[2];
                if (name.indexOf(".") != -1) {
                    name = name.substr(0, name.lastIndexOf("."));
                }
                if(name==""){
                    continue;
                }
                resultlist[name.toLowerCase()]=1;
            }
            callback(resultlist);
        });
    }
}


function getPatinCountry(country){
    switch (country){
        case "ussr":
            return "russian";
        case "france":
            return "french";
        case "usa":
            return "american";
        case "uk":
            return "british";
        case "china":
            return "chinese";
        case "czech":
            return "czech";
        case "japan":
            return "japan";
        case "germany":
            return "german";
        default: return"";
    }
}