var util = require('util');
var path = require('path');
var fs = require('fs');
var utils = require('utils');
var Service = require('Service');

/**
 * 获得文件和目录列表
 */
var GetFileList = function() { 
  Service.call(this);
  this.sqlInject.exclude = ['dir'];
};

util.inherits(GetFileList, Service);

module.exports = GetFileList;

/**
 * 处理服务请求
 * @param  {Object} req 服务请求对象
 * @param  {Object} res 服务响应对象
 */
GetFileList.prototype.process =  function(req, res) {
  if(!req.dir) {
    this.onLogicError(1, '请提供目录路径！');
    return;
  }

  req.dir = req.dir.replace(/\.\.\//g,'').replace(/\.\//g,'');
  var dirPath = utils.getPath(req.dir);

  var self = this;
  res.dirs = [];
  res.files = [];
	fs.readdir(dirPath, function(err, list) {
    if(err) {
      self.onLogicError(1, '读取目录信息出错：'+err.message);
      return;
    }
    var pending = list.length;
    if (list.length==0) {
      self.end(res);
      return;
    }
    list.forEach(function(fileName) {
      var dir = path.resolve(dirPath, fileName);
      fs.stat(dir, function(err, stat) {
        if (stat) {
          if(stat.isDirectory()) {
            res.dirs.push({type:'dir', name: fileName, mtime: stat.mtime});
          } else {
            if(req.exts) {
              if(req.exts.contains(path.extname(fileName))) {
                res.files.push({type:'file', name: fileName, mtime: stat.mtime, size: stat.size});
              }
            } else {
              res.files.push({type:'file', name: fileName, mtime: stat.mtime, size: stat.size});
            }
          }
        }
        if (!--pending) {
          res.dirs.sort(utils.compare("name"));
          res.files.sort(utils.compare("name"));
          self.end(res);
          return;
        }
      });
    });
  });
};