const request = require('request');


function streamDownload(){
  this.downloadCallback = null;
}

streamDownload.prototype.showProgress = function(recv, total){
  this.percentAge = (recv * 100) / total;
  this.downloadCallback('progress', this.percentAge);
}

streamDownload.prototype.downloadFile = function(patchUrl, localPath, callback){
  this. downloadCallback = callback;
  this.recvBytes = 0;
  this.totalBytes = 0;

  const req = request({
    method: 'GET',
    uri: patchUrl
  });

  log.info("[TAG-DOWNLOAD] start download url: "+patchUrl);
  const out = fs.createWriteStream(localPath);
  req.pipe(out);

  req.on('response', (data)=>{
    this.totalBytes = parseInt(data.headers['Content-Length'], 10);
    log.info('[TAG-DOWNLOAD] start download size:'+this.totalBytes);
  });

  req.on('data', (chunk)=>{
    this.recvBytes += chunk.length;
    this.showProgress(this.recvBytes, this.totalBytes);
  });

  req.on('end', ()=>{
    log.info('[TAG-DOWNLOAD] download success!');
    this.downloadCallback('finished', this.percentAge);
  });
}

const StreamDownload = new streamDownload();
