var util = require('util');
var path = require('path');
var fs = require('fs');
var utils = require('utils');
var Service = require('Service');
var mime = require('../../../../config/mime');

/**
 * 上传文件
 */
var DownloadFile = function() { 
  Service.call(this);
  this.sqlInject.exclude = ['dir', 'fileName'];
};

util.inherits(DownloadFile, Service);

module.exports = DownloadFile;

/**
 * 处理服务请求
 * @param  {Object} req 服务请求对象
 * @param  {Object} res 服务响应对象
 */
DownloadFile.prototype.process =  function(req, res) {
  if(!req.filePath) {
    this.onLogicError(1, '请提供文件路径！');
    return;
  }
  let filePath = utils.getPath(req.filePath);
  let fileName = path.basename(filePath);
  var self = this;
  fs.stat(filePath, function (err, stats) { 
    var ext = path.extname(filePath);
    ext = ext ? ext.slice(1) : 'unknown';
    var contentType = mime[ext] || 'application/octet-stream';
    if(!(ext=='jpg'||ext=='jpeg'||ext=='png'||ext=='bmp'||ext=='gif')) {
      req.socket.httpResponse.setHeader('Content-Disposition', 
        'attachment; filename='+encodeURIComponent(fileName));
    }
    req.socket.httpResponse.setHeader('Content-Type', contentType);
    req.socket.httpResponse.setHeader('Content-Length', stats.size);
    req.socket.httpResponse.setHeader('Accept-Ranges', 'none');
    req.socket.httpResponse.writeHead(200, 'ok');

    var readStream = fs.createReadStream(filePath);
    self.fileStream = readStream;
    self.lastActive = new Date();
    self.isEnd = false;
    setTimeout(function(){self.checkTimeout(req,res);},1000);
    
    readStream.pipe(req.socket.httpResponse);
    readStream.on('data',function(chunk){
      self.lastActive = new Date();
    });
    
    readStream.on('end', function(err2) {
      self.isEnd = true;
      req.socket.httpResponse.end();
      if(err2) {
        logger.log('发送文件时发生意外错误，错误描述：'+err2.message, req._requestId);
        return;
      }
      logger.log('文件['+fileName+']发送完毕。', req._requestId);
    });
      
    req.socket.httpResponse.setTimeout(30*1000, function(){
      logger.log('响应超时。', req._requestId);
      req.socket.httpResponse.end();
    });
  });
};

DownloadFile.prototype.checkTimeout = function(req,res) {
  var self = this;
  if(!self.isEnd){
    var timelong = ((new Date()).getTime()-self.lastActive.getTime())/1000;
    if(timelong>10){
      logger.log(req._requestId+' 下载文件10秒无响应，超时。');
      req.socket.httpResponse.end();
      if(self.fileStream){
        try {
          self.fileStream.close();
        } catch(err) {}
      }
    }else{
      setTimeout(function(){
        self.checkTimeout(req,res);
      },1000);
    }
  }
};