/**
 * Created by adri1 on 2014/12/18.
 */

var ModBakManager = function() {
    this.db = new Config("modbakmanager.db");
}
ModBakManager.prototype= {
    //获取新id
    getNewId: function () {
        var max = 0;
        for (var i in this.db.json) {
            if (max < Number(i)) {
                max = Number(i);
            }
        }
        return (max + 1).toString();
    },
    scanMods: function () {
        //遍历游戏目录文件夹
        //找目录下面有当前版本目录的就是备份库
        //如果不认识该备份库就自动添加
        //自动生成名称
        var manager = this;
        var gamepath = config.get('path');
        if (checkERROR(gamepath)) {
            return;
        }
        if (!fs.existsSync(gamepath)) {
            return;
        }
        var rec={}
        for (var i in this.db.json) {
            if(!fs.existsSync(this.db.get(i).path)||this.db.get(i).path.toLowerCase() in rec){
                console.log("remove out bak",this.db.get(i));
                //删除不存在的记录
                this.db.remove(i);
            }else{
                rec[this.db.get(i).path.toLowerCase()]=1;
            }
        }
        var files = fs.readdirSync(gamepath);
        files.forEach(function (file, index) {
            var curPath = gamepath + "/" + file;
            if (fs.statSync(curPath).isDirectory()) { //对所有目录遍历
                var bak = fs.readdirSync(curPath);
                bak.forEach(function (file2, index) {
                    if (file2 == config.get("gameversion")) { //对所有目录遍历
                        //检查是不是已知目录
                        var check=manager.getBakByPath(curPath.toLowerCase());
                        //添加未知目录
                        if(checkERROR(check)){
                            manager.newMods(curPath.toLowerCase());
                        }
                    }
                });
            }
        });
    },
    newMods: function (bakpath, name) {
        //新建一个备份库
        var newid = this.getNewId();
        if (checkERROR(name)) {
            name = "bak" + newid;
        }
        var nm = {
            id: newid,
            path: this.toPath(bakpath),
            name: name
        }
        this.db.set(nm.id, nm);
        return nm;
    },
    setMods: function(id,mods){
        this.db.set(id, mods);
    },
    //切换当前res_mods
    changeBak: function (id) {
        var target=this.getBakById(id);
        if(checkERROR(target)){
            return;
        }
        var gamepath=config.get('path');
        var mpath=this.toPath(gamepath+"/res_mods/");
        var now=this.getBakByPath(mpath);
        if(checkERROR(now)){
            now=this.newMods(mpath);
        }
        fs.renameSync(now.path,this.toPath(gamepath+"/res_mods_"+now.name+"/"));//将当前mods重命名
        now.path=this.toPath(gamepath+"/res_mods_"+now.name+"/");
        this.setMods(now.id,now);
        fs.renameSync(target.path,mpath);//将目标mods重命名
        target.path=mpath;
        this.setMods(target.id,target);
    },
    getBakById: function (id) {
        return this.db.get(id);
    },
    getBakByPath: function (bakpath) {
        bakpath=this.toPath(bakpath.toLowerCase());
        for (var i in this.db.json) {
            if(this.db.json[i].path.toLowerCase()==bakpath){
                return this.db.get(i);
            }
        }
        return null;
    },
    toPath:function(filepath){
        filepath+="/"
        return filepath.replace(/\\/g, "/").replace(/\/\//g, "/");
    }
}
var modbak=new ModBakManager();

function modbakpage() {
    checkNowPage("modbak",true);
    if ($("#modlist").html().length > 0) {
        $("#modlist").html("");
    }
    modbak.scanMods();
    $("#modlist").load("modbak.html #modbak", function (data) {
        if(checkNowPage("modbak",false)){
            return;
        }
        for (var i in modbak.db.json) {
            var bak = modbak.getBakById(i);
            var tr = "<tr id='baktr" + bak.id + "'>";
            tr += "<td class='stext id'>" + bak.id + "</td>";
            tr += "<td class='stext path'>" + bak.path + "</td>";
            tr += "<td class='stext bakname name'>" + bak.name + "</td>";
            tr += "<td><button class='btn btn-sm btn-info bakbak '>备份</button>&nbsp;<button class='btn btn-sm btn-success bakuse '>启用</button>&nbsp;<button class='btn btn-sm btn-warning bakdel'>删除</button></td>";
            tr += "</tr>";
            $("#modbaktbody").append(tr);
            //当前
            if (bak.path.toLowerCase() == (modbak.toPath(config.get('path') + "/res_mods/").toLowerCase())) {
                $("#baktr" + bak.id).find('.bakuse').first().addClass('disabled');
                $("#baktr" + bak.id).find('.bakdel').first().addClass('disabled');
                $("#baktr" + bak.id).css('background-color', 'rgba(255, 215, 0, 0.4)');
            }
        }
        $(".bakname").dblclick(function(){
            var oldname=$(this).text();
            var input='<input class="baknamemod" type="text" value="'+oldname+'">';
            $(this).html(input);
            $(".baknamemod").dblclick(function(){
                var newname=$(this).val();
                var id=$(this).parent().parent().attr('id').substring(5);
                modbak.db.json[id].name=newname;
                modbak.db.update();
                $(this).parent().text(newname);
                modbakpage();
            });
        })
        $(".bakuse").click(function () {
            var id = $(this).parent().parent().children(".id").text();
            modbak.changeBak(id);
            modbakpage();
        });
        $(".bakdel").click(function () {
            var id = $(this).parent().parent().children(".id").text();
            var paths = $(this).parent().parent().children(".path").text();
            customConfirm("删除插件备份将删除整个"+modbak.db.get(id)['path']+"文件夹，请确认删除",function(){
                deleteFolderRecursive(paths, -1);
                modbak.db.remove(id);
                modbakpage();
            });
        });
        $(".bakbak").click(function () {
            var id = $(this).parent().parent().children(".id").text();
            var paths = $(this).parent().parent().children(".path").text();
            var name = $(this).parent().parent().children(".name").text();
            var newid = modbak.getNewId();
            var gamepath = config.get('path');
            var uid=getUniqueId();
            var t=new Tips(uid);
            t.init(name + "插件集备份","备份程序初始化<br/>");
            if (!fs.existsSync(gamepath + "/res_mods_bak" + newid)) {
                fs.mkdirSync(gamepath + "/res_mods_bak" + newid);
            }
            if (!fs.existsSync(gamepath + "/res_mods_bak" + newid + "/" + config.get("gameversion"))) {
                fs.mkdirSync(gamepath + "/res_mods_bak" + newid + "/" + config.get("gameversion"));
            }
            var cm = new CopyManager(uid, name + "插件集备份", false, null, function () {
                t.append("备份程序结束<br/>");
                if (nowpage == "modbak") {
                    modbakpage();
                }
                setTimeout(function () {
                    t.remove();
                }, 5000);
            });
            cm.add(paths, gamepath + "/res_mods_bak" + newid);
            t.append("备份程序开始<br/>");
            cm.start();
        });
        $("#newbakbutton").click(function (e) {
            var id = modbak.getNewId();
            var gamepath = config.get('path');
            fs.mkdirSync(gamepath + "/res_mods_bak" + id);
            fs.mkdirSync(gamepath + "/res_mods_bak" + id + "/" + config.get("gameversion"));
            modbak.changeBak(modbak.newMods(gamepath + "/res_mods_bak" + id, 'bak' + id).id);
            modbakpage();
        });
    });
}