var cleverInstallDirname = 'tempInstall';
function cleverinstallpage() {
    if(!checkNowPage("cleverinstall",true)){
        return;
    }
    if ($("#modlist").html().length > 0) {
        $("#modlist").html("");
    }
    $("#modlist").load("cleverInstall.html #clever", function (data) {
        if(checkNowPage("cleverinstall",false)){
            return;
        }
        $("#cleverinstallbutton").click(function () {
            cleverselect("install");
        });
        $("#cleverdeletebutton").click(function () {
            cleverselect("delete");
        });
    });
}

function cleverselect(mode) {
    if (checkERROR(config.get('path'))) {
        customAlert("请先在沙盘设置中设置游戏路径。", "warning");
        return;
    }
    chooseFile(function (data) {
        var file = unescape(data);
        var id = getUniqueId();
        var modid=modManager.newModRecord(file, null, getFileName(file), id);
        new CleverInstaller(id, getFileName(file), file, mode,false,modid);
    });
}

var CleverInstaller = function (id, name, file, mode,overwrite, modid) {
    this.uid = id;
    this.file = file;
    this.mode = mode;
    this.name = name;
    this.modid = modid;
    this.overwrite=overwrite;
    this.start();
}
CleverInstaller.prototype = {
    start: function () {
        var ci=this;
        if(!fs.existsSync(this.file)){
            return;
        }
        var ext = this.file.substr(this.file.lastIndexOf('.')).trim().toLowerCase();
        var tip = new Tips(this.uid);
        var oper = "安装";
        if (this.mode != "install") {
            oper = "卸载"
        }
        tip.init(this.name + oper, '开始准备内容<br/>');
        if (this.mode == 'install') {
            if(!fs.existsSync(cleverInstallDirname)) {
                fs.mkdirSync(cleverInstallDirname, 0755);  //位置不存在时创建
            }
            if (ext=='.otf' || ext=='.ttf') {
                tip.remove();
                this.installFont();
            } else {
                unCompress(this.file,this.uid,function(list){ci.analyseFileList(list)});
            }
        }else if (this.mode == 'delete') {
            if (ext=='.otf' || ext=='.ttf') {
                return;
            } else {
                listCompress(this.file,function(list){ci.analyseFileList(list)});
            }
        }
    },

    //安装字体文件
    installFont:function(){
        var spawn=cp.spawn("fontview.exe",[this.file]);
        spawn.stdout.on('end', function () {
            new Tips(this.uid).remove();
        });
    },

    analyseFileList: function (filelist) {
        $("#progress").append("<br/>开始进行分析");
        new Tips(this.uid).html('开始进行分析');
        //第一层目录是版本号
        var versionInstall = false;
        //前缀文件夹安装
        var prefixList = new Object();
        var versionList = new Object();
        var copybak = new Object();
        var installFileList = [];
        for (var i in filelist) {
            var file = filelist[i].trim().replace(/\\/g, "/");
            //安装时，临时目录有此文件，或卸载模式
            if(fs.existsSync(cleverInstallDirname + "\\" + this.uid+"\\"+file)){
                var stat = fs.lstatSync(cleverInstallDirname + "\\" + this.uid+"\\"+file);
                //只考虑文件
                if (stat.isDirectory()) {
                    continue;
                }
            }else if(this.mode=='delete'){
                if(file.indexOf('.zip')!=-1||file.indexOf('.7z')!=-1||file.indexOf('.rar')!=-1||file.indexOf('.wbp')!=-1){
                    continue;
                }
            }else{
                //文件不存在
                continue;
            }
            var dirs = file.split("/")
            for (var x in dirs) {
                var y = Number(x);
                var dir = dirs[x];
                if (dir == "res_mods") {
                    if (y == 0) {
                        //resmods是根目录，可以直接安装
                        installFileList[file] = config.get('path') + "/" + file;
                    }
                    else {
                        //resmods不是根目录，记录前缀
                        var prefix = file.substr(0, file.indexOf("/" + dir + "/"));
                        prefixList[prefix] = prefix;
                        installFileList[file] = config.get('path') + "/" + file.substr(file.indexOf("res_mods/"));
                    }
                    //记录子目录名
                    if (dirs.length > y + 2 && dirs[y + 1] && dirs[y + 1].split(".").length == 3) {
                        copybak[dirs[y + 2]] = dirs[y + 2];
                    }
                    //已找到resmods，继续对下一条检测
                    break;
                }
                else if (dir == "res") {
                    if (y == 0) {
                        //res是根目录
                        installFileList[file] = config.get('path') + "/" + file.replace("res/", "res_mods/" + config.get("gameversion"));
                    }
                    else {
                        //res不是根目录，记录前缀
                        var prefix = file.substr(0, file.indexOf("/" + dir + "/"));
                        prefixList[prefix] = prefix;
                        installFileList[file] = config.get('path') + "/" + file.substr(file.indexOf("res/")).replace("res/", "res_mods/" + config.get("gameversion"));
                    }
                    //记录子目录名
                    if (dirs.length > y + 1) {
                        console.log("copybak", dirs[y + 1]);
                        copybak[dirs[y + 1]] = dirs[y + 1];
                    }
                    //已找到res，继续对下一条检测
                    break;
                }
                else if (dir.split(".").length == 4) {
                    versionInstall = true;
                    versionList[dir] = dir;
                    //使用版本号安装
                    if (y == 0) {
                        if (dir == config.get("gameversion")) {
                            installFileList[file] = config.get('path') + "/res_mods/" + file;
                        }else{
                            installFileList[file] = config.get('path') + "/res_mods/" + config.get("gameversion")+"/"+file.substr(file.indexOf("/"));
                        }
                    }
                    else {
                        var prefix = file.substr(0, file.indexOf("/" + dir + "/"));
                        prefixList[prefix] = prefix;
                        installFileList[file] = config.get('path') + "/res_mods/" + config.get("gameversion") + "/" + file.substr(file.indexOf("/",file.indexOf(dir)+1));
                    }
                    //记录子目录名
                    if (dirs.length > y + 1) {
                        console.log("copybak", dirs[y + 1]);
                        copybak[dirs[y + 1]] = dirs[y + 1];
                    }
                    break;
                }
                else if (this.checkDetail(dir)) {
                    if (y == 0) {
                        installFileList[file] = config.get('path') + "/res_mods/" + config.get("gameversion") + "/" + file;
                    }
                    else {
                        var prefix = file.substr(0, file.indexOf("/" + dir + "/"));
                        prefixList[prefix] = prefix;
                        installFileList[file] = config.get('path') + "/res_mods/" + config.get("gameversion") + "/" + file.substr(file.indexOf("/" + dir + "/"));
                    }
                    console.log("copybak", dir);
                    copybak[dir] = dir;
                    break;
                }
            }
        }
        this.prepareFileList(versionInstall, prefixList, versionList, copybak, installFileList)
    },
    prepareFileList: function (versionInstall, prefixList, versionList, copybak, installFileList) {
        $("#progress").append("<br/>分析完毕");
        var prefixChoose = new Object();
        var prefixLength = prefixList.length;
        var prefixInstall = false;
        var tip = new Tips(this.uid);
        console.log("length", prefixLength, versionInstall, prefixList);
        var type = "";
        var msg = "";
        var ci=this;
        //$("#modconfirmlog" + this.uid).hide();
        //当前状态提示
        msg += "插件准备完成<br/>";
        //$("#modconfirmmsg" + this.uid).append("文件  <span style='color:red;'>[" + filename + "]</span>  准备完成<br/>");

        var oper = "安装";
        if (this.mode != "install") {
            oper = "卸载"
        }
        //版本号目录安装,提示,不需要选择
        if (versionInstall) {
            msg += "存在以下插件版本:<br/>";
            //$("#modconfirmmsg" + this.uid).append("存在以下插件版本:<br/>");
            for (var x in versionList) {
                msg += x + "<br/>";
                $("#modconfirmmsg" + this.uid).append(x + "<br/>");
            }
            msg += "将会" + oper + "到最新版本" + config.get("gameversion");
            //$("#modconfirmmsg" + this.uid).append("将会" + oper + "最新版本" + newestVersion + "(如无最新版本则不" + oper + ")");
        }
        //前缀安装
        if (prefixLength > 0) { //多个前缀选项,选择一个或多个
            prefixInstall = true;
            msg += "存在多个插件目录,请选择将要" + oper + "的目录:<br/>"
            //          $("#modconfirmmsg" + this.uid).append("存在多个插件目录,请选择将要" + oper + "的目录:<br/>");
            for (var x in prefixList) {
                msg += "<input class='clcb' type='checkbox' value='" + x + "'>" + x + "<br/>"
                //            $("#modconfirmmsg" + this.uid).append("<input class='clcb' type='checkbox' value='" + x + "'>" + x + "<br/>");
            }
            tip.html(msg);
            //生成选择框
            this.createConfirm(msg);
            $("#modcancel" + this.uid).on("click", function () {
                $(this).parent().parent().alert('close');
                ci.clearTemp();
            });
            $("#modconfirm" + this.uid).on("click", function () {
                $(this).parent().parent().alert('close');
                ci.executeFileList(prefixChoose, prefixInstall, installFileList, copybak);
            });
            //切换勾选状态
            $(".clcb").on("click", function () {
                if ($(this)[0].checked) {
                    console.log("add", $(this).attr("value"));
                    prefixChoose[$(this).attr("value")] = $(this).attr("value");
                } else {
                    console.log("del", $(this).attr("value"));
                    delete prefixChoose[$(this).attr("value")];
                }
            });
        } else {
            if (prefixLength == 1) { //只有一个前缀选项, 不需要选择
                msg += "将" + oper + "&nbsp;"
                //           $("#modconfirmmsg" + this.uid).append("将" + oper + "&nbsp;")
                for (var t in prefixList) {
                    msg += "<span style='color:red;'>" + t + "</span>";
                    //$("#modconfirmmsg" + this.uid).append("<span style='color:red;'>" + t + "</span>");
                }
                msg += "&nbsp;下的插件<br/>";
                //         $("#modconfirmmsg" + this.uid).append("&nbsp;下的插件，请确认" + oper + "<br/>");
            }
            tip.html(msg);
            this.executeFileList(prefixChoose, prefixInstall, installFileList, copybak);
        }
        $("#third").show();
        //console.log("copybak", copybak);
        //console.log("installFileList", installFileList);
    },
    executeFileList: function (prefixChoose, prefixInstall, installFileList, copybak) {
        var list = installFileList;
        var manager;
        var tip = new Tips(this.uid);
        var ci=this;
        var callback = function (id, name, copybak) {
            var cm = new CopyManager(id, name + " 依赖文件复制", false, null, function () {
                //完成复制
                //提示完成，延迟删除
                if(ci.mode=="install") {
                    tip.append("<br/>插件安装完成<br/>");
                }else if(ci.mode=="delete"){
                    tip.append("<br/>插件卸载完成<br/>");
                }
                message.send(name + "完成", "success");
                $("#progress").append("<br/>"+name + "完成");
                setTimeout(function () {
                    tip.remove();
                }, 10000);
            });
            for (var i in copybak) {
                if (needCopyBak(i)) {
                    cm.add(config.get('path') + "\\res\\" + i + "\\", config.get('path') + "\\res_mods\\" + config.get("gameversion")  + "\\" + i + "\\");
                    //customAlert("检查到依赖项目" + i + "，自动进行复制，请耐心等待全部复制完成提示(第一次需要几分钟)", "warning");
                    tip.append("检查到依赖项目" + i + "<br/>")
                    $("#progress").append("<br/>复制依赖目录:" + config.get('path') + "\\res\\" + i + "&nbsp;到目录:" + config.get('path') + "\\res_mods\\" + config.get("gameversion")  + "\\" + i + "\\");
                }
            }
            cm.start();
            deleteFolderRecursive(cleverInstallDirname+"/"+ci.uid,-1);
        }
        if (this.mode == "install") {
            manager = new CopyManager(this.uid, this.name + '安装', true, copybak, callback);
            $("#progress").append("<br/>安装开始");
            tip.append("<br/>安装开始");
        } else {
            manager = new DeleteManager(this.uid, this.name + '卸载', true, copybak, callback);
            $("#progress").append("<br/>删除开始");
            tip.append("<br/>删除开始");
        }
        var testlist=new Array();
        for (var source in list) {
            var target = list[source].trim();
            //判断是否包含所选prefix
            if (prefixInstall) {
                console.log("choose", prefixChoose);
                var noPrefix = true;
                for (var prefix in prefixChoose) {
                    if (source.indexOf(prefix) != -1) {
                        noPrefix = false;
                        break;
                    }
                }
                if (noPrefix) {
                    continue;
                }
            }
            if (this.mode == 'delete') {
                //跳过特殊文件
                var path=target.replace(/\//g, "\\").trim().toLowerCase();
                var fname = getFileName(path);
                if (fname == "cameranode.pyc" || path.indexOf("scripts\\client\\mods\\__init__.pyc")!=-1 || fname == "") {
                    continue;
                }
            }
            //复制或删除!!!添加记录
            manager.add(cleverInstallDirname + "\\" + this.uid + "\\" + source, target);
            //文件检测列表
            testlist.push(toPath(target));
        }
        if(testlist.length==0||this.mode != "install"||this.overwrite) {
            //添加完成开始执行
            manager.start();
        }else{
            var ci=this;
            var result=modrecord.testFileList(testlist);
            var x=0;
            var msg='<div><span style="color:red;">'+this.name+'</span>&nbsp;与以下插件存在冲突<small>(选择卸载或不选择直接覆盖)</small></div>';
            for(var i in result){
                if(i.toString()==this.modid.toString()){
                    continue;
                }
                x++;
                //处理基本数据
                var name='';
                var unknown=false;
                if(i=='unknown'){
                    unknown=true;
                    name='未知文件';
                }else{
                    var m=modManager.getLocalMod(i);
                    if(checkERROR(m)){
                        m=modManager.getRemoteMod(i);
                    }
                    if(checkERROR(m)){
                        name='未知插件';
                        unknown=true;
                    }else{
                        name= m.name;
                    }
                }
                //列出冲突插件
                msg+='<div class="'+(unknown?0:i)+'">';
                if(!unknown){
                    msg += "<input class='concb' type='checkbox' value='" + i + "'>";
                }else{
                    msg += "<input class='concb' disabled='disabled' title='无法卸载' type='checkbox' value='" + i + "'>";
                }
                msg+='&nbsp;'+name+'</div>';
            }
            if(x==0){
                for (var i in manager.list) {
                    var f = manager.list[i];
                    modrecord.updateRecord(f.split("#####")[1], ci.modid);
                }
                manager.start();
            }else {
                //执行处理
                //执行安装
                //生成选择框
                this.createConfirm(msg);
                $('#modconfirm' + this.uid).click(function (e) {
                    //执行选择需要卸载的插件
                    var dm = new DeleteManager(getUniqueId(), '卸载冲突插件', true, null, function () {
                        for (var i in manager.list) {
                            var f = manager.list[i];
                            modrecord.updateRecord(f.split("#####")[1], ci.modid);
                        }
                        manager.start();
                    });
                    $(this).parent().parent().alert('close');
                    $('.concb:checked').each(function (e) {
                        var id = $(this).attr('value');
                        var list = modrecord.getUninstallFile(id);
                        for (var i in list) {
                            dm.add(list[i], list[i]);
                        }
                    });
                    dm.start();
                });
                $('#modcancel' + this.uid).click(function () {
                    //删除已解压的文件
                    $(this).parent().parent().alert('close');
                    new Tips(ci.uid).remove();
                    deleteFolderRecursive(cleverInstallDirname + '/' + ci.uid, -1);
                });
            }
        }
    },


    checkDetail: function (file) {
        switch(file) {
            case "gui":
            case "content":
            case "audio":
            case "texts":
            case "scripts":
            case "maps":
            case "materials":
            case "particles":
            case "settings":
            case "sfx":
            case "shaders":
            case "spaces":
            case "system":
            case "Trees":
            case "vehicles":
                return true;
            default :
                return false;
        }
    },
    clearTemp: function () {
        deleteFolderRecursive(cleverInstallDirname + "/" + this.uid,-1);
    },
    createConfirm: function (msg) {
        $('#alert').append('<div class="alert alert-danger fade in" id="modconfirmlog' + this.uid + '"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button><p><strong id="modconfirmmsg' + this.uid + '">' + msg + '</strong></p><p><button type="button" id="modconfirm' + this.uid + '" class="btn btn-success">确认</button><button type="button" id="modcancel' + this.uid + '" style="margin-left:10px;" class="btn btn-primary">取消</button></p></div>');
    }
}

function unCompress(file,uid,callback){
    var ext=file.substr(file.lastIndexOf("."));
    if (ext == '.zip' || ext == '.wbp') {
        unZip(file,uid,callback);
    } else if (ext == '.rar') {
        unRar(file,uid,callback);
    } else if (ext == '.7z') {
        un7z(file,uid,callback);
    } else {
        customAlert('不支持的类型:' + ext, 'danger');
    }
}
function listCompress(file,callback){
    var ext=file.substr(file.lastIndexOf("."));
    if (ext == '.zip' || ext == '.wbp') {
        listZip(file,callback);
    } else if (ext == '.rar') {
        listRar(file,callback);
    } else if (ext == '.7z') {
        list7z(file,callback);
    } else {
        customAlert('不支持的类型:' + ext, 'danger');
    }
}

function unZip(file,uid,callback) {
    //解压并分析文件列表
    $("#progress").append("<br/>已选择文件" + file+",开始准备内容<br/>");

    if(checkERROR(config.get("bakUnzip"))||!config.get("bakUnzip")) {
        var spawn = cp.spawn("apps\\exe\\unzip.exe", ["-o", file, '-d', cleverInstallDirname + "\\" + uid]);
        var bufs = [];
        spawn.stdout.on('data', function (data) {
            bufs.push(data);
        });
        spawn.stdout.on('end', function () {
            var buf = Buffer.concat(bufs);
            var output = buf.toString();
            if (output.length > 0) {
                var lines = output.split('\n');
                var list = [];
                for (var i in lines) {
                    var line = lines[i];
                    var words = line.split(uid + "/");
                    if (words[1]) {
                        list.push(words[1]);
                    }
                }
                //console.log(list);
                if (typeof(callback) == "function") {
                    callback(list);
                }
            }
        });
        spawn.stderr.on('data', function (data) {
            console.log('exec error:' + repairCharset(data));
            customAlert("解压失败:" + repairCharset(data), 'danger');
        });

    }else {
        var zip = new AdmZip(file);
        zip.extractAllTo(cleverInstallDirname + "\\" + uid + "\\", true);
        var zipEntries = zip.getEntries(); // an array of ZipEntry records
        var list = [];
        zipEntries.forEach(function (zipEntry) {
            list.push(zipEntry.entryName);
        });
        if (typeof(callback) == "function") {
            callback(list);
        }
    }
}

function unRar(file,uid,callback) {
    //解压并分析文件列表
    $("#progress").append("<br/>已选择文件" + file+",开始准备内容");
    console.log("\"apps\\exe\\UnRAR.exe\" x \"" + file + "\" " + cleverInstallDirname + "\\" + uid);
    var spawn=cp.spawn("apps\\exe\\UnRAR.exe",["x",file,cleverInstallDirname + "\\" + uid + "\\"]);
    var bufs = [];
    spawn.stdout.on('data', function (data) {
        bufs.push(data);
    });
    spawn.stdout.on('end', function () {
        var buf = Buffer.concat(bufs);
        var output = buf.toString();
        if (output.length > 0) {
            var lines = output.split('\n');
            var list = [];
            for (var i in lines) {
                var line = lines[i];
                if (line.indexOf(uid) != -1) {
                    var words = line.split(uid);
                    var sidx = words[1].lastIndexOf("\\");
                    var eidx = words[1].indexOf(" ", sidx);
                    words = words[1].substring(1, eidx);
                    if (words) {
                        list.push(words);
                    }
                }
            }
            console.log(list);
            if (typeof(callback) == "function") {
                callback(list);
            }
        }
    });
    spawn.stderr.on('data', function (data) {
        console.log('exec error:' + repairCharset(data));
        customAlert("解压失败:" + repairCharset(data), 'danger');
    });
}
function un7z(file,uid,callback){
    $("#progress").append("<br/>已选择文件" + file+",开始准备内容");
    console.log("\"apps\\exe\\7za.exe\" x \"" + file + "\" -o" + cleverInstallDirname + "\\" + uid);

    var spawn=cp.spawn("apps\\exe\\7za.exe",["x",file,'-o'+cleverInstallDirname + "\\" + uid + "\\"]);
    var bufs = [];
    spawn.stdout.on('data', function (data) {
        bufs.push(data);
    });
    spawn.stdout.on('end', function () {
        var buf = Buffer.concat(bufs);
        var output = buf.toString();
        if (output.length > 0) {
            var lines = output.split('\n');
            var list = [];
            for (var i in lines) {
                var line = lines[i];
                if (line.indexOf('Extracting') != -1) {
                    var words = line.split('Extracting');
                    console.log(words);
                    list.push(words[1].trim());
                }
            }
            console.log(list);
            if (typeof(callback) == "function") {
                callback(list);
            }
        }
    });
    spawn.stderr.on('data', function (data) {
        console.log('exec error:' + repairCharset(data));
        customAlert("解压失败:" + repairCharset(data), 'danger');
    });
}

function listZip(file,callback){
    console.log("listZip("+file+")");
    var zip = new AdmZip(file);
    var zipEntries = zip.getEntries(); // an array of ZipEntry records
    var list = [];
    zipEntries.forEach(function(zipEntry) {
        list.push(zipEntry.entryName);
    });
    callback(list);
}

function listRar(file,callback){
    console.log("listRar("+file+")");
    var spawn=cp.spawn("apps\\exe\\UnRAR.exe",["l",file]);
    var bufs = [];
    spawn.stdout.on('data', function (data) {
        bufs.push(data);
    });
    spawn.stdout.on('end', function () {
        var buf = Buffer.concat(bufs);
        var output = buf.toString();
        if (output.length > 0) {
            var lines = output.split('\n');
            var list=[];
            for (var i in lines) {
                var line = lines[i];
                var p=line.split(' ');
                for (var j in p){
                    if(p[j].indexOf('.')!=-1) {
                        var y = p[j].trim();
                        list.push(y);
                    }
                }
            }
            if (typeof(callback) == "function") {
                callback(list);
            }
        }
    });
    spawn.stderr.on('data', function (data) {
        console.log('exec error:' + repairCharset(data));
        customAlert("解压失败:" + repairCharset(data), 'danger');
    });
}

function list7z(file,callback){
    console.log("list7z("+file+")");

    var spawn=cp.spawn("apps\\exe\\7za.exe",["l",file]);
    var bufs = [];
    spawn.stdout.on('data', function (data) {
        bufs.push(data);
    });
    spawn.stdout.on('end', function () {
        var buf = Buffer.concat(bufs);
        var output = buf.toString();
        if (output.length > 0) {
            var lines = output.split('\n');
            var list=[];
            for (var i in lines) {
                var line = lines[i];
                var p=line.split(' ');
                for (var j in p){
                    if(p[j].indexOf('.')!=-1) {
                        var y = p[j].trim();
                        list.push(y);
                    }
                }
            }
            if (typeof(callback) == "function") {
                callback(list);
            }
        }
    });
    spawn.stderr.on('data', function (data) {
        console.log('exec error:' + repairCharset(data));
        customAlert("解压失败:" + repairCharset(data), 'danger');
    });
}

function needCopyBak(paths) {
    return (paths == "audio" || paths == "influx" || paths == "text");
}