var DownloadCenter = function(){
    this.running = false;
    this.list= new Array();
}

DownloadCenter.prototype = {
    add: function (url, savefile, name, callback){
        var dt=new DownloadTask(url, savefile, name, callback);
        this.list.push(dt);
        this.run();
    },
    run: function (){
        if(this.running){
            return;
        }
        this.running=true;
        while (this.list.length>0){
            var dt=this.list.shift();
            this.download(dt);
        }
        this.running=false;
    },

    oldDownload: function(dt) {
        console.log('download', dt.url, 'to', dt.savefile)
        var urlinfo = urlparse(dt.url);
        var options = {
            method: 'GET',
            host: urlinfo.host,
            path: urlinfo.pathname
        };
        if(urlinfo.port) {
            options.port = urlinfo.port;
        }
        if(urlinfo.search) {
            options.path += urlinfo.search;
        }
        var req = http.request(options, function(res) {
            var writestream = fs.createWriteStream(dt.savefile);
            writestream.on('close', function() {
                if (typeof(dt.callback)=="function"){
                    dt.callback(dt.savefile);
                }
            });
            res.pipe(writestream);
        });
        req.on('uncaughtException', function (err) {
            customAlert("网络错误:"+err.toString(),'danger');
        });
        req.end();
    },

    download:function(dt) {
        console.log('download', dt.url, 'to', dt.savefile)
        fs.exists("apps\\exe\\downloadTool.exe",function(exists){
            if (exists){
                var ok=false;
                var dl=cp.spawn("apps\\exe\\downloadTool.exe",[dt.url,dt.savefile]);
                var id=message.send(dt.name+'下载中','info');
                var tip=new Tips(id);
                tip.init(dt.name+"下载","下载中<br/>")
                tip.append("<div class='prog"+id+"'></div>");
                dl.stdout.on('data', function (data) {
                    var cout=repairCharset(data).split("\n");
                    for (var i in cout){
                        var line=cout[i].trim();
                        if (IsNum(line)){
                            ok=true;	//没出现过数字，视作下载失败
                            updateProgress(id,line);
                        }else if(line!=""){
                            customAlert("错误:"+line,'danger');
                            ok=false;
                        }
                    }
                });
                dl.stderr.on('data', function (data) {
                    customAlert("错误:"+repairCharset(data),'danger');
                    ok=false;
                });
                dl.on('exit',function(){
                  //  $("#"+msgid).alert("close");
                    if(ok){
                        $(".prog"+id).remove();
                        tip.append("下载完成")
                        message.close(id);
                        message.send(dt.name+'已完成下载','success');
                        if (typeof(dt.callback)=="function"){
                            dt.callback(dt.savefile);
                        }
                        setTimeout(function () {
                            tip.remove();
                        }, 3000);
                    }else{
                        customAlert("使用备用下载程序",'warning');
                        downloadCenter.oldDownload(dt);
                    }
                });
                dl.on('uncaughtException', function (err) {
                    customAlert("网络错误:"+repairCharset(err),'danger');
                });
            }
            else {
                customAlert("下载程序被误杀，请重新覆盖沙盘并在杀毒软件中添加信任",'warning');
                customAlert("尝试使用备用下载程序",'warning');
                downloadCenter.oldDownload(dt);
            }
        });
    }
}

var DownloadTask = function(url, savefile, name, callback) {
    this.url = url;
    this.savefile = savefile;
    this.name = name;
    this.callback = callback;
}

var downloadCenter = new DownloadCenter();
