var newestVersion = '0.9.4';
var clevelInstallDirname = 'tempInstall';
function cleverinstallpage() {
    if ($("#modlist").html().length > 0) {
        $("#modlist").html("");
    }
    $("#modlist").load("cleverInstall.html #clever", function (data) {
        $("#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();
        new CleverInstaller(id, getFileName(file), file, mode);
        modManager.newModRecord(file, null, getFileName(file), id);
    });
}

var CleverInstaller = function (id, name, file, mode) {
    this.uid = id;
    this.file = file;
    this.mode = mode;
    this.name = name;
    this.start();
}
CleverInstaller.prototype = {
    start: function () {
        var ext = this.file.substr(this.file.lastIndexOf('.')).trim().toLowerCase();
        if (ext == '.zip'||ext=='.wbp') {
            this.filelistZip(this);
        } else if (ext == '.rar') {
            this.filelistRar(this);
        } else if (ext == '.7z') {
            this.filelist7z(this);
        } else {
            customAlert('不支持的类型:' + ext, 'danger');
        }
    },
    filelistZip: function (cleverinstall) {
        //解压并分析文件列表
        var name = getFileName(this.file);
        $("#progress").append("<br/>已选择文件" + this.file);
        console.log("\"apps\\exe\\unzip.exe\" -o \"" + this.file + "\" -d " + clevelInstallDirname + "\\" + this.uid);
        var spawn = cp.exec("\"apps\\exe\\unzip.exe\" -o \"" + this.file + "\" -d " + clevelInstallDirname + "\\" + this.uid, {encoding: 'binary'}, function (err, stdout, stderr) {
            if (err != null) {
                console.log('exec error:' + stderr + '|' + repairCharset(err));
                customAlert("解压失败:" + repairCharset(err), 'danger');
                return;
            }
            if (stderr.length > 0) {
                console.log('stderr: ' + stderr + '|' + repairCharset(stderr));
                customAlert("解压失败" + repairCharset(stderr), 'danger');
                return;
            }
            var output = repairCharset(stdout);
            if (output.length > 0) {
                var lines = output.split('\n');
                var list = [];
                for (var i in lines) {
                    var line = lines[i];
                    var words = line.split(cleverinstall.uid + "/");
                    if (words[1]) {
                        list.push(words[1]);
                    }
                }
                console.log(list);
                cleverinstall.analyseFileList(name, list);
            }
        });
    },

    filelistRar: function (cleverinstall) {
        //解压并分析文件列表
        var name = getFileName(this.file);
        $("#progress").append("<br/>已选择文件" + this.file);
        console.log("\"apps\\exe\\UnRAR.exe\" x \"" + this.file + "\" " + clevelInstallDirname + "\\" + this.uid);
        var spawn = cp.exec("\"apps\\exe\\UnRAR.exe\" x \"" + this.file + "\" " + clevelInstallDirname + "\\" + this.uid + "\\", {encoding: 'binary'}, function (err, stdout, stderr) {
            if (err != null) {
                console.log('exec error:' + repairCharset(err));
                customAlert("解压失败:" + repairCharset(err), 'danger');
                return;
            }
            if (stderr.length > 0) {
                console.log('stderr: ' + repairCharset(stderr));
                customAlert("解压失败" + repairCharset(stderr), 'danger');
                return;
            }
            var output = repairCharset(stdout);
            if (output.length > 0) {
                var lines = output.split('\n');
                var list = [];
                for (var i in lines) {
                    var line = lines[i];
                    if (line.indexOf(cleverinstall.uid) != -1) {
                        var words = line.split(cleverinstall.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);
                cleverinstall.analyseFileList(name, list);
            }
        });
    },
    filelist7z: function(cleverinstall){
        var name = getFileName(this.file);
        $("#progress").append("<br/>已选择文件" + this.file);
        console.log("\"apps\\exe\\7za.exe\" x \"" + this.file + "\" -o" + clevelInstallDirname + "\\" + this.uid);
        var spawn = cp.exec("\"apps\\exe\\7za.exe\" x \"" + this.file + "\" -o" + clevelInstallDirname + "\\" + this.uid + "\\", {encoding: 'binary'}, function (err, stdout, stderr) {
            if (err != null) {
                console.log('exec error:' + repairCharset(err));
                customAlert("解压失败:" + repairCharset(err), 'danger');
                return;
            }
            if (stderr.length > 0) {
                console.log('stderr: ' + repairCharset(stderr));
                customAlert("解压失败" + repairCharset(stderr), 'danger');
                return;
            }
            var output = repairCharset(stdout);
            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');
                        var sidx = words[1].lastIndexOf(" ");
                        list.push( words[1].substring(sidx));
                    }
                }
                console.log(list);
                cleverinstall.analyseFileList(name, list);
            }
        });
    },
    analyseFileList: function (filename, filelist) {
        $("#progress").append("<br/>开始进行分析");
        //第一层目录是版本号
        var versionInstall = false;
        //前缀文件夹安装
        var prefixList = new Array();
        var versionList = new Array();
        var copybak = new Array();
        var installFileList = [];
        for (var i in filelist) {
            var file = filelist[i].trim().replace(/\\/g, "/");
            if(fs.existsSync(clevelInstallDirname + "\\" + this.uid+"\\"+file)){
                var stat = fs.lstatSync(clevelInstallDirname + "\\" + this.uid+"\\"+file);
                //只考虑文件
                if (stat.isDirectory()) {
                    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/" + newestVersion);
                    }
                    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/" + newestVersion);
                    }
                    //记录子目录名
                    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 == 3) {
                    versionInstall = true;
                    versionList[dir] = dir;
                    //使用版本号安装
                    if (y == 0) {
                        if (dir == newestVersion) {
                            installFileList[file] = config.get('path') + "/res_mods/" + file;
                        }
                    }
                    else {
                        var prefix = file.substr(0, file.indexOf("/" + dir + "/"));
                        prefixList[prefix] = prefix;
                        if (dir == newestVersion) {
                            installFileList[file] = config.get('path') + "/res_mods/" + file.substr(file.indexOf(dir));
                        }
                    }
                    //记录子目录名
                    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/" + newestVersion + "/" + file;
                    }
                    else {
                        var prefix = file.substr(0, file.indexOf("/" + dir + "/"));
                        prefixList[prefix] = prefix;
                        installFileList[file] = config.get('path') + "/res_mods/" + newestVersion + "/" + file.substr(file.indexOf("/" + dir + "/"));
                    }
                    console.log("copybak", dir);
                    copybak[dir] = dir;
                    break;
                }
            }
        }
        this.prepareFileList(filename, versionInstall, prefixList, versionList, copybak, installFileList)
    },
    prepareFileList: function (filename, versionInstall, prefixList, versionList, copybak, installFileList) {
        $("#progress").append("<br/>分析完毕");
        var prefixChoose = new Array();
        var prefixLength = prefixList.length;
        var prefixInstall = false;
        var tip = new Tips(this.uid);
        console.log("length", prefixLength, versionInstall, prefixList);
        var type = "";
        var msg = "";
        //$("#modconfirmlog" + this.uid).hide();
        //当前状态提示
        msg += "插件准备完成<br/>";
        //$("#modconfirmmsg" + this.uid).append("文件  <span style='color:red;'>[" + filename + "]</span>  准备完成<br/>");

        var oper = "安装";
        if (this.mode != "install") {
            oper = "卸载"
        }
        tip.init(this.name + 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 + "最新版本" + newestVersion + "(如无最新版本则不" + oper + ")";
            //$("#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/>");
            }
            //生成选择框
            this.createConfirm(msg);
            $("#modcancel" + this.uid).on("click", function () {
                $(this).parent().parent().alert('close');
                this.clearTemp();
            });
            $("#modconfirm" + this.uid).on("click", function () {
                $(this).parent().parent().alert('close');
                this.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/>");
            }
            this.executeFileList(filename, prefixChoose, prefixInstall, installFileList, copybak);
        }
        tip.append(msg);
        $("#third").show();
        console.log("copybak", copybak);
        console.log("installFileList", installFileList);
    },
    executeFileList: function (filename, 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/>");
                }else if(ci.mode=="delete"){
                    tip.append("插件卸载完成<br/>");
                }
                message.send(name + "完成", "success");
                $("#progress").append(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\\" + newestVersion + "\\" + i + "\\");
                    //customAlert("检查到依赖项目" + i + "，自动进行复制，请耐心等待全部复制完成提示(第一次需要几分钟)", "warning");
                    tip.append("检查到依赖项目" + i + "<br/>")
                    $("#progress").append("<br/>复制依赖目录:" + config.get('path') + "\\res\\" + i + "&nbsp;到目录:" + config.get('path') + "\\res_mods\\" + newestVersion + "\\" + i + "\\");
                }
            }
            cm.start();
            deleteFolderRecursive(clevelInstallDirname+"/"+this.uid,-1);
        }
        if (this.mode == "install") {
            manager = new CopyManager(this.uid, this.name + '安装', true, copybak, callback);
            $("#progress").append("<br/>安装开始");
        } else {
            manager = new DeleteManager(this.uid, this.name + '卸载', true, copybak, callback);
            $("#progress").append("<br/>删除开始");
        }
        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 name = getFileName(target.replace(/\//g, "\\")).trim();
                if (name == "CameraNode.pyc" || name == "__init__.pyc" || name == "") {
                    continue;
                }
            }
            //复制或删除!!!添加记录
            manager.add(clevelInstallDirname + "\\" + this.uid + "\\" + source, target);
        }
        //添加完成开始执行
        manager.start();
    },


    checkDetail: function (file) {
        if (file == "gui" || file == "audio" || file == "influx" || file == "text" || file == "scripts" || file == "vehicles") {
            return true;
        }
        return false;
    },
    clearTemp: function () {
        deleteFolderRecursive(clevelInstallDirname + "/" + 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 listZip(file,extlist,callback){
    console.log("listZip("+file+")");
    var spawn = cp.exec("\"apps\\exe\\unzip.exe\" -l \"" + file + "\"", {encoding: 'binary'}, function (err, stdout, stderr) {
        if (err != null) {
            console.log('exec error:' + repairCharset(err));
            customAlert("解压失败:" + repairCharset(err), 'danger');
            return;
        }
        if (stderr.length > 0) {
            console.log('stderr: ' + repairCharset(stderr));
            customAlert("解压失败" + repairCharset(stderr), 'danger');
            return;
        }
        var output = repairCharset(stdout);
        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){
                    var y=p[j].trim();
                    var idx=y.lastIndexOf('.')
                    if(idx!=-1&&idx> y.length-6&&idx< y.length-2){
                        var ext= y.substr(y.lastIndexOf('.'));
                        for (var x in extlist){
                            var c=extlist[x];
                            if(ext==c){
                                list.push(y);
                                console.log(y);
                                break;
                            }
                        }
                    }
                }
            }
            if (typeof(callback) == "function") {
                callback(list);
            }
        }
    });
}

function listRar(file,extlist,callback){
    console.log("listRar("+file+")");
    var spawn = cp.exec("\"apps\\exe\\UnRAR.exe\" l \"" + file + "\"", {encoding: 'binary'}, function (err, stdout, stderr) {
        if (err != null) {
            console.log('exec error:' + repairCharset(err));
            customAlert("解压失败:" + repairCharset(err), 'danger');
            return;
        }
        if (stderr.length > 0) {
            console.log('stderr: ' + repairCharset(stderr));
            customAlert("解压失败" + repairCharset(stderr), 'danger');
            return;
        }
        var output = repairCharset(stdout);
        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){
                    var y=p[j].trim();
                    var idx=y.lastIndexOf('.')
                    if(idx!=-1&&idx> y.length-6&&idx< y.length-2){
                        var ext= y.substr(y.lastIndexOf('.'));
                        for (var x in extlist){
                            var c=extlist[x];
                            if(ext==c){
                                list.push(y);
                                console.log(y);
                                break;
                            }
                        }
                    }
                }
            }
            if (typeof(callback) == "function") {
                callback(list);
            }
        }
    });
}

function list7z(file,extlist,callback){
    console.log("list7z("+file+")");
    var spawn = cp.exec("\"apps\\exe\\7za.exe\" l \"" + file + "\"", {encoding: 'binary'}, function (err, stdout, stderr) {
        if (err != null) {
            console.log('exec error:' + repairCharset(err));
            customAlert("解压失败:" + repairCharset(err), 'danger');
            return;
        }
        if (stderr.length > 0) {
            console.log('stderr: ' + repairCharset(stderr));
            customAlert("解压失败" + repairCharset(stderr), 'danger');
            return;
        }
        var output = repairCharset(stdout);
        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){
                    var y=p[j].trim();
                    var idx=y.lastIndexOf('.')
                    if(idx!=-1&&idx> y.length-6&&idx< y.length-2){
                        var ext= y.substr(y.lastIndexOf('.'));
                        for (var x in extlist){
                            var c=extlist[x];
                            if(ext==c){
                                list.push(y);
                                console.log(y);
                                break;
                            }
                        }
                    }
                }
            }
            if (typeof(callback) == "function") {
                callback(list);
            }
        }
    });
}

function needCopyBak(path) {
    if (path == "audio" || path == "influx" || path == "text") {
        return true;
    }
    return false;
}