var Service = require('Service');
var util = require('util');

/**
 * 删除附件缓存
 */
var ClearAttachCache = function() { 
  Service.call(this);
};

util.inherits(ClearAttachCache, Service);

module.exports = ClearAttachCache;

/**
 * 处理服务请求
 * @param  {Object} req 服务请求对象
 * @param  {Object} res 服务响应对象
 */
ClearAttachCache.prototype.process =  function(task) {
  var saveDays = 7;
  if(server.config.Attach && server.config.Attach.cacheSaveDays)
    saveDays = parseInt(server.config.Attach.cacheSaveDays);
  logger.log('正在清理过期的附件缓存...');
  var validKeys = [];
  for(var key in server.attachs) {
    var file = server.attachs[key];
    if(((new Date())-(new Date(file.lastDown)))>(saveDays*24*60*60*1000)) {
      validKeys.push(key);
    }
  }
  for(var i=0;i<validKeys.length;i++) {
    delete server.attachs[validKeys[i]];
  }
  logger.log('清理完毕，本次共清理 '+validKeys.length+' 条附件缓存。');
  validKeys = null;
  this.end();
};