var urlparse = require('url').parse
    , http = require('http')
    , fs = require('fs')
    , path = require("path");
var cp = require('child_process');
var AdmZip = require('adm-zip');
var iconv = require('iconv-lite');
var message = 0;
var readedmessage = 0;


//检测参数是否存在
function checkERROR(check) {
    return check === null || check === undefined;
}

//解析路径获得文件名
function getFileName(paths) {
    return (paths.lastIndexOf("/") < 0) ? ((paths.lastIndexOf("\\") < 0) ? "" : paths.substring(paths.lastIndexOf("\\") + 1)) : paths.substring(paths.lastIndexOf("/") + 1);
}

var MessageCenter=function(){
    this.msgList=new Array();
}
MessageCenter.prototype={
    send: function(msg, type) {
        var id = getUniqueId();
        $("#messagepage").prepend('<div class="alert alert-' + type + ' fade in" id="msg' + id + '"><button type="button" class="close" data-dismiss="alert" aria-hidden="true" style="font-size:2em;">×</button>' + msg + '<div class="prog'+id+'"></div></div>')
        this.msgList.push(id);
        this.updateMsgbadge();
        return id;
    },
    updateMsgbadge: function(){
        if (this.msgList.length == 0) {
            $("#msgbadge").text('');
        } else {
            $("#msgbadge").text(this.msgList.length);
        }
    },
    read:function(){
        this.msgList=new Array();
        this.updateMsgbadge();
    },
    close: function(id){
        $("#msg"+id).remove();
    }
}

//更新下载进度
function updateProgress(id, value) {
    var prog = '<div class="progress progress-striped active"><div class="progress-bar progress-bar-success"  role="progressbar" aria-valuenow="' + value + '" aria-valuemin="0" aria-valuemax="100" style="width: ' + value + '%"><span>' + value + '%</span></div></div>';
    $(".prog"+id).html(prog);
}

function customAlert(msg, type, time) {
    var id = message.send(msg, type);
    $('#alert').append('<div class="alert customalert alert-' + type + ' fade in alert' + id + '"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + msg + '</div>')
    if (checkERROR(time)) {
        time = 3000;
    }
    window.setTimeout(function () {
        $(".alert" + id).alert('close');
    }, time);
}

function customConfirm(msg, callback) {
    var id = getUniqueId();
    $('#alert').append('<div class="alert alert-danger fade in" id="confirmlog' + id + '"><button type="button" class="close" data-dismiss="alert" aria-hidden="true"><i class="fa fa-times"></i></button><p><strong id="confirmmsg' + id + '">' + msg + '</strong></p><p><button type="button" id="confirm' + id + '" class="btn btn-success">确认</button><button type="button" id="cancel' + id + '" style="margin-left:10px;" class="btn btn-primary">取消</button></p></div>');
    $("#confirm" + id).on("click", function () {
        $(this).parent().parent().alert('close');
        if (typeof(callback) == "function") {
            callback();
        }
    });
    $("#cancel" + id).on("click", function () {
        $(this).parent().parent().alert('close');
    });
    //}
}

//去除乱码
function repairCharset(oldstr) {
    var str = iconv.decode(oldstr, 'gbk');
    return str;
}

//去除乱码2
function repairCharsetString(oldstr) {
    var str = iconv.decode(new Buffer(oldstr, ['binary']), 'gbk');
    return str;
}
var Tips = function(id){
    this.uid=id;
}
Tips.prototype={
    init:function(title,msg){
        var str = '<div class="popover bottom" id="tips'+this.uid+'"><div class="arrow"></div><h3 class="popover-title" style="color:red;">'+title+'</h3><div class="popover-content"><div class="tipsmsg">'+msg+'</div><div class="prog'+this.uid+'"></div><div class="merge'+this.uid+'"></div></div>';
        $("#tips").append(str);
    },
    append:function(msg){
        $("#tips"+this.uid).children(".popover-content").children('.tipsmsg').append(msg);
    },
    remove:function(){
        $("#tips"+this.uid).remove();
    },
    html:function(msg){
        $("#tips"+this.uid).children(".popover-content").children('.tipsmsg').html(msg);
    }
}

//文件复制管理
var CopyManager = function (id, name, overwrite, obj,finishCallback) {
    //相关流程的id
    this.uid = id;
    //相关文件或操作的名称
    this.name = name;
    //是否覆盖目标文件
    this.overwrite = overwrite;
    //结束时的处理
    this.finishCallback = finishCallback;
    //后续处理的传入参数
    this.obj = obj;
    //待复制列表
    this.list = new Array();
    this.enable = true;
    new Tips(id).append("<div id='prog"+this.uid+"'></div>");
}

CopyManager.prototype = {
    addDir: function (src, dst) {
        var files = fs.readdirSync(src);
        var list = this.list;
        var cm=this;
        files.forEach(function (file) {
            var pathname = src + '/' + file;
            if(!fs.existsSync(pathname)){
                return;
            }
            var stat = fs.lstatSync(pathname);
            console.log('addDir', src, dst, file);
            if (!stat.isDirectory()) {
                list.push(src + '/' + file + "#####" + dst + '/' + file);
            } else {
                cm.addDir(src + '/' + file, dst + '/' + file);
            }
        });
    },
    add: function (src, dst) {    //添加需要复制的文件和地址
        //文件夹则遍历其中文件
        if(!fs.existsSync(src)){
            return;
        }
        var stat = fs.lstatSync(src);
        var cm = this;
        if (stat.isDirectory()) {
            this.addDir(src, dst);
        } else {
            cm.list.push(src + "#####" + dst);
        }
    },
    remove:function(target){
        for(var i in cm.list){
            
        }
    },
    checkDirExist: function (src, dst, callback) {
        var dirs = dst.replace(/\//g, "\\").split('\\');
        var nowdir = dirs[0];
        for (var i = 1; i < dirs.length - 1; i++) {
            nowdir = nowdir + '\\' + dirs[i];
            if (!fs.existsSync(nowdir)) {
                fs.mkdirSync(nowdir);
            }
        }
        callback(src,dst);
    },
    start: function () {
        //进度提示板
        this.next();
    },
    next: function () {         //添加完成后启动复制
        if (this.list.length == 0) {
            this.enable = false;
            $("#prog"+this.uid).remove();
            if (typeof(this.finishCallback) == "function") {
                this.finishCallback(this.uid, this.name, this.obj);
            }
            delete this;
            return;
        }
        $("#prog"+this.uid).html("<p>剩余 " + this.list.length + " 项复制</p>");
        var paths = this.list.shift().split("#####");
        //进行复制
        console.log(paths[0], paths[1]);
        this.copy(toPath(paths[0]), toPath(paths[1]));
    },
    copy: function (src, dst) {
        var overwrite = this.overwrite;
        var cm = this;
        if (fs.existsSync(src)&&(!fs.existsSync(dst) || overwrite)) {
            this.checkDirExist(src, dst, function (src, dst) {
                var fileReadStream = fs.createReadStream(src);
                var fileWriteStream = fs.createWriteStream(dst);
                fileReadStream.pipe(fileWriteStream);
                fileWriteStream.on('close', function () {
                    console.log(dst + ' copy over');
                    //如果还可以复制，复制下一个文件
                    if (cm.enable) {
                        cm.next();
                    }
                });
            });
        } else {
            if (this.enable) {
                this.next();
            }
        }
    }
}

var DeleteManager = function (id, name, overwrite, obj, finishCallback) {
    this.list = new Array();
    this.uid=id;
    this.name=name;
    //结束时的处理
    this.finishCallback = finishCallback;
    //后续处理的传入参数
    this.obj = obj;
    this.dir = false;//删除文件夹
    new Tips(id).append("<div id='prog"+this.uid+"'></div>");
}
DeleteManager.prototype = {
    add: function (src, dst) {
        this.list.push(dst);
    },
    start: function () {
        while (this.list.length > 0) {
            var i = this.list.shift();
            if(fs.existsSync(i)){
                try{
                    if(!fs.lstatSync(i).isDirectory()) {
                        fs.unlinkSync(i);
                    }else if (this.dir){
                        deleteFolderRecursive(i,-1);
                    }
                }
                catch(e){
                    delFile(i);
                }
            }
        }
        $("#prog" + this.uid).text(this.name+"已全部完成");
        if (typeof(this.finishCallback) == "function") {
            this.finishCallback(this.uid, this.name, this.obj);
        }
        delete this;
    }
}
var tray=null;
//最小化到托盘
function min2tray() {
    if(checkERROR(tray)){
		tray = new gui.Tray({ icon: 'apps\\index\\wows\\css\\wows.png' });
		tray.on('click', function () {
			win.show();
		});
	}
    win.hide();
}
function chooseFile(callback,dir) {
    if(checkERROR(dir)){
        dir=false;
    }
    var chooser = $('#fileDialog');
    if(dir){
        chooser.attr("nwdirectory","");
    }else{
        chooser.removeAttr("nwdirectory");
    }
    chooser.change(function (evt) {
        console.log($(this).val());
        var cfile = $(this).val();
        if (typeof(callback) == "function") {
            callback(cfile);
            $('#fileDialog').replaceWith('<input style="display:none;" id="fileDialog" type="file" />');
        }
    });
    chooser.trigger('click');
}

function moveFolderRecursive(bases,target) {
    if( fs.existsSync(bases) ) {
        var files = fs.readdirSync(bases);
        files.forEach(function(file,index){
            var curPath = bases + "/" + file;
            var curTarget=target + "/" + file;
            if(!fs.existsSync(target)){
                fs.mkdirSync(target,0755);
            }
            if(fs.statSync(curPath).isDirectory()) { //
                if(!fs.existsSync(curTarget)) {
                    fs.renameSync(curPath, curTarget);
                }else {
                    moveFolderRecursive(curPath, curTarget);
                }
            } else { // delete file
                if(fs.existsSync(curTarget)) {
                   fs.unlinkSync(curTarget);
                }
                fs.renameSync(curPath, curTarget);
            }
        });
    }
}
function deleteFolderRecursive(paths,keep) {
    if( fs.existsSync(paths) ) {
        var files = fs.readdirSync(paths);
        files.forEach(function(file,index){
            var curPath = paths + "/" + file;
            if(fs.statSync(curPath).isDirectory()) { // recurse
                deleteFolderRecursive(curPath,keep-1);
            } else { // delete file
				try{
					fs.unlinkSync(curPath);
				}
				catch(e){
                    delFile(curPath);
				}
                console.log("del",curPath);
            }
        });
        if(keep<0) {
			try{
				fs.rmdirSync(paths);
			}
			catch(e){
                rmdir(paths);
			}
            console.log("rmdir",paths);
        }
    }
}
function findFolderRecursive(paths,findfile,findidx){
    var res="";
    try{
        if(checkERROR(paths)){
            return "";
        }
        if(checkERROR(findfile)){
            return "";
        }
        if( fs.existsSync(paths) ) {
            var files = fs.readdirSync(paths);
            files.forEach(function(file,index){
                var curPath = paths + "/" + file;
                if(fs.statSync(curPath).isDirectory()) { // recurse
                    if(findidx<2) {
                        var templist = findFolderRecursive(curPath, findfile, findidx + 1);
                        if (templist != "") {
                            res=templist;
                        }
                    }
                } else { // file
                    if(file.toLowerCase()==findfile.toLowerCase()){
                        res=curPath;
                    }
                    //console.log("list",curPath);
                }
            });
        }
    }catch(e){

    }
    return res;
}
//列出文件,dir列出文件夹
function listFolderRecursive(paths,dir){
    if(checkERROR(paths)){
        return;
    }
    if(checkERROR(dir)){
        dir=false;
    }
    var list=[];
    if( fs.existsSync(paths) ) {
        var files = fs.readdirSync(paths);
        files.forEach(function(file,index){
            var curPath = paths + "/" + file;
            if(fs.statSync(curPath).isDirectory()) { // recurse
                var templist=listFolderRecursive(curPath,dir);
                list=list.concat(templist);
            } else { // file
                list.push(curPath);
                //console.log("list",curPath);
            }
        });
    }
    if(dir){
        list.push(paths);
    }
    return list;
}

function date2str(x, y) {
    var z = {y: x.getFullYear(), M: x.getMonth() + 1, d: x.getDate(), h: x.getHours(), m: x.getMinutes(), s: x.getSeconds()};
    return y.replace(/(y+|M+|d+|h+|m+|s+)/g, function (v) {
        return ((v.length > 1 ? "0" : "") + eval('z.' + v.slice(-1))).slice(-(v.length > 2 ? v.length : 2))
    });
}

function refreshClass() {
    $(".double").each(function () {
        var val = Number($(this).text());
        if (isNaN(val)) {
            val = 0;
        }
        if (val != 0) {
            $(this).text(val.toFixed(2));
        } else {
            $(this).text(0);
        }
    });
    $(".toppercent").each(function () {
        var val = Number($(this).text());
        if (isNaN(val)) {
            val = 0;
        }
        $(this).text(val.toFixed(1) + '%');
    });
    $(".int").each(function () {
        var val = Number($(this).text());
        if (isNaN(val) || (val < 0 && val > -1)) {
            val = 0;
        }
        $(this).text(val.toFixed(0));
    });
    $(".percent").each(function () {
        var val = Number($(this).text());
        if (isNaN(val)) {
            val = 0;
        }
        $(this).text((val * 100).toFixed(0) + '%');
    });
    $(".detailpercent").each(function () {
        var val = Number$((this).text());
        if (isNaN(val)) {
            val = 0;
        }
        $(this).text(Number(val * 100).toFixed(1) + '%');
    });
}

function getUniqueId() {
    var d = new Date();
    return d.getTime()
}

function IsNum(s) {
    if (s != null && s != "") {
        return !isNaN(s);
    }
    return false;
}

function fillZero(num){
    if(num<10){
        return "0"+num;
    }else{
        return num;
    }
}

function delFile(file){
    cp.exec("del /F \"" + file + "\"", {encoding: 'binary'}, function (err, stdout, stderr) {
        if (err) {
            console.log("del fail " + repairCharsetString(err), "danger");
        }
        if (stdout) {
            console.log("stdout", repairCharsetString(stdout));
        }
        if (stderr) {
            console.log("1", repairCharsetString(stderr));
        }
        console.log("del", file);
    });
}
function rmdir(file){
    cp.exec("rmdir /S/Q \"" + file + "\"", {encoding: 'binary'}, function (err, stdout, stderr) {
        if (err) {
            console.log("rmdir fail " + repairCharsetString(err), "danger");
        }
        if (stdout) {
            console.log("stdout", repairCharsetString(stdout));
        }
        if (stderr) {
            console.log("1", repairCharsetString(stderr));
        }
        console.log("rmdir", file);
    });
}

function dateFormat(date){
    return date.year+1900+"-"+(date.month+1)+"-"+date.date+" "+date.hours+":"+date.minutes;
}

function getType(id){
    var a=['success','default','primary','info','warning','danger'];
    return a[id % a.length];
}
function getShipById(id){
    for(var k in shipDict){
        if(shipDict[k]['id']==id){
            return shipDict[k];
        }
    }
    return null;
}

var imageout=false;
function showImage(img,desc) {
    if(img!=""){
        imageout=false;
        var top =0;
        var left=0;
        if(window.innerHeight-event.clientY>500) {
            top = event.clientY + 50;
        }else{
            top= window.innerHeight - 450;
        }
        if(window.innerWidth-event.clientX>400) {
            left = event.clientX + 50;
        }else{
            left=window.innerWidth-1150;
        }
        if($(".a1").find("img.lazy").first().attr('data-original')==img){
            $(".a1").css("top", document.body.scrollTop + top-92);
            $(".a1").css("left", document.body.scrollLeft + left);
            $(".a1").show();
        }else {
            var id = getUniqueId();
            var t1 = "<div style='margin: 0 auto 0 auto'><img id='img" + id + "' class='lazy middleimg' data-original='" + img + "'></div><div >" + desc + "</div>";
            $(".a1").html(t1);
            $(".a1").css("top", document.body.scrollTop + top-92);
            $(".a1").css("left", document.body.scrollLeft + left);
            $(".a1").show();
            setTimeout(function () {
                $('#img' + id).lazyload({
                    effect: "fadeIn"
                });
            }, 200);
        }
    }
}
function hideImage() {
    imageout=true;
    setTimeout(function () {
        if(imageout) {
            $(".a1").hide();
        }
    }, 200);
}

function versionFormat(ver){
	if(checkERROR(ver)){
		return "0.0.0";
	}
    var s=ver.split(".");
    if(s.length<3){
        return ver;
    }
    return s[0]+"."+s[1]+"."+s[2];
}
var message=new MessageCenter();