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

//切换坦克和战机
function changeApp(path, game, autochange) {	//autochange==false 强制转换
    if (autochange && (checkERROR(config.get('autochangegame')) || !config.get('autochangegame'))) {
        //不切换  记录原因
        console.log(autochange, checkERROR(config.get('autochangegame')), config.get('autochangegame'))
        return;
    }
    //记录上次的类型
    config.set('game',game);
    monitorStop();
    window.open(path, '_self');
}

//关闭所有监控程序
function monitorStop() {
    try {
        wotStop();
    } catch (e) {
    }
    try {
        wowpStop();
    } catch (e) {
    }
    try {
        replayStop();
    } catch (e) {
    }
}

//关闭坦克监控程序
function wotStop() {
    if (!checkERROR(monitor) && monitor) {
        console.log("kill monitor");
        monitor.kill();
        monitor = null;
    }
}

//关闭坦克录像监控程序
function replayStop() {
    if (!checkERROR(replayMonitor) && replayMonitor) {
        console.log("kill");
        replayMonitor.kill();
        replayMonitor = null;
    }
}

//关闭战机监控程序
function wowpStop() {
    if (!checkERROR(wowpmonitor) && wowpmonitor) {
        console.log("kill wowpmonitor");
        wowpmonitor.kill();
        wowpmonitor = null;
    }
}

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

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

//执行sql
function executeSql(sql, db, callback, nothingcallback) {
    var sth = false;
    var es = cp.spawn("apps\\dossier\\main.exe", [db, sql]);
    var bufs = [];
    es.stdout.on('data', function (data) {
        bufs.push(data);
        sth = true;
    });
    es.stderr.on('data', function (data) {
        customAlert("错误:" + repairCharset(data), 'danger');
        sth = true;
    });
    es.stdout.on('end', function () {
        var buf = Buffer.concat(bufs);
        var output = buf.toString();
        if (output.length > 0 && typeof(callback) == "function") {
            callback(output);
        }
    });
    es.on('exit', function () {
        if (!sth && typeof(nothingcallback) == "function") {
            nothingcallback();
        }
    });
}

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');
    });
    //}
}

//通过tankid获取坦克信息
function getTankByVid(vid) {
    for (var i in tanksjson) {
        var tank = tanksjson[i];
        if (tank.compDescr == vid) {
            return tank;
        }
    }
    return null;
}

//通过mapid获取地图名称
function getMapByMid(mid) {
    for (var i in mapsjson) {
        var map = mapsjson[i];
        if (map.mapid == mid) {
            return map;
        }
    }
    return null;
}

//通过飞机id获取飞机信息
function getPlaneByPid(pid) {
    for (var i in planesjson) {
        var plane = planesjson[i];
        if (Number(plane.planeid) == Number(pid)) {
            return plane;
        }
    }
    return null;
}

//去除乱码
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='tips'+id;
}
Tips.prototype={
    init:function(title,msg){
        var str = '<div class="popover bottom" id="'+this.uid+'"><div class="arrow"></div><h3 class="popover-title" style="color:red;">'+title+'</h3><div class="popover-content">'+msg+'</div></div>';
        $("#tips").append(str);
    },
    append:function(msg){
        $("#"+this.uid).children(".popover-content").append(msg);
    },
    remove:function(){
        $("#"+this.uid).remove();
    },
    html:function(msg){
        $("#"+this.uid).children(".popover-content").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;
        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 {
                this.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 {
            this.checkDirExist(src, dst, function (src, dst) {
                cm.list.push(src + "#####" + dst);
            });
        }
    },
    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 path = this.list.shift().split("#####");
        //进行复制
        console.log(path[0], path[1]);
        this.copy(path[0], path[1]);
    },
    copy: function (src, dst) {
        var overwrite = this.overwrite;
        var cm = this;
        if (fs.existsSync(src)&&(!fs.existsSync(dst) || overwrite)) {
            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;
    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)){
                fs.unlinkSync(i);
            }
        }
        $("#prog" + this.uid).text("删除已全部完成");
        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\\css\\战争沙盘.png' });
		tray.on('click', function () {
			win.show();
		});
	}
    win.hide();
}
function chooseFile(callback) {
    var chooser = $('#fileDialog');
    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 deleteFolderRecursive(path,keep) {
    if( fs.existsSync(path) ) {
        var files = fs.readdirSync(path);
        files.forEach(function(file,index){
            var curPath = path + "/" + file;
            if(fs.statSync(curPath).isDirectory()) { // recurse
                deleteFolderRecursive(curPath,keep-1);
            } else { // delete file
				try{
					fs.unlinkSync(curPath);
				}
				catch(e){
				}
                console.log("del",curPath);
            }
        });
        if(keep<0) {
			try{
				fs.rmdirSync(path);
			}
			catch(e){
			}
            console.log("rmdir",path);
        }
    }
}

function listFolderRecursive(path,dir){
    if(checkERROR(path)){
        return;
    }
    if(checkERROR(dir)){
        dir=false;
    }
    var list=[];
    if( fs.existsSync(path) ) {
        var files = fs.readdirSync(path);
        files.forEach(function(file,index){
            var curPath = path + "/" + 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(path);
    }
    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;
}
var message=new MessageCenter();