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

DownloadCenter.prototype = {
    add: function (url, savefile, name, callback,prefix,block){
        var dt=new DownloadTask(url, savefile, name, callback, prefix, block);
        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() {
                var id=message.send(dt.name+'下载中','info');
                var tip=new Tips(id);
                tip.append("下载完成")
                message.close(id);
                message.send(dt.name+'已完成下载','success');
                setTimeout(function () {
                    tip.remove();
                }, 3000);
                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', encodeURI(dt.url), 'to', dt.savefile)
        if(!fs.existsSync(path.dirname(dt.savefile))) {
            fs.mkdirSync(path.dirname(dt.savefile), 0755);  //下载位置不存在时创建
        }
        var dl=cp.spawn(baseurl+"dossier\\main.exe",['download',encodeURI(dt.url),dt.savefile,dt.block,dt.prefix]);
        var id=message.send(dt.name+'开始下载','info');
        var tip=new Tips(id);
        var fail=false;
        tip.init(dt.name+"下载","下载中<br/>")
        tip.append("<div id='filesize"+id+"'></div>")
        dl.stdout.on('data', function (data) {
            var cout=repairCharset(data).split("\n");
            for (var i in cout){
                var line=cout[i].trim();
                //console.log(line);
                if(line.indexOf("#")!=-1){
                    var n=line.split("#");
                    $("#filesize"+id).html("已下载:\t"+n[1]+"MB / "+n[0]+"MB");
                    updateProgress(id,n[2]);
                }else if (line.indexOf("$")!=-1){
                    $(".merge"+id).html("合并文件:"+line.substr(1));
                }else{
                    console.log(line);
                    if(line.indexOf("FAIL")!=-1){
                        fail=true;
                    }
                }
            }
        });
        dl.stderr.on('data', function (data) {
            customAlert("错误:"+repairCharset(data),'danger');
            fail=true;
        });
        dl.on('exit',function(){
          //  $("#"+msgid).alert("close");
            if(!fail){
                $(".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{
                if(dt.block==3){
                    tip.remove();
                    customAlert("使用备用下载程序",'warning',15000);
                    downloadCenter.oldDownload(dt,id);
                }else{
                    customAlert("重试次数过多，请重新点击下载续传",'warning',15000);
                    tip.remove();
                }
            }
        });
        dl.on('uncaughtException', function (err) {
            customAlert("网络错误:"+repairCharset(err),'danger');
        });
    }
}

var DownloadTask = function(url, savefile, name, callback, prefix, block) {
    this.url = url;
    this.savefile = savefile;
    this.name = name;
    this.callback = callback;
    if(checkERROR(prefix)){
        this.prefix='tempInstall/'
    }else{
        this.prefix = prefix;
    }
    if(checkERROR(block)){
        this.block = 3;
    }else{
        this.block = block;
    }
}

var downloadCenter = new DownloadCenter();
