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

/**
 * 获得项目列表
 */
var GetList = function() { 
  Service.call(this);
};

util.inherits(GetList, Service);

module.exports = GetList;

/**
 * 处理服务请求
 * @param  {Object} req 服务请求对象
 * @param  {Object} res 服务响应对象
 */
GetList.prototype.process =  function(req, res) {
	var self = this;
	var results = [];
	var dirRoot = utils.getPath("/app");

  fs.readdir(dirRoot, function(err, list) {
    if(err) {
      self.onLogicError(1, '读取目录信息出错：'+err.message);
      return;
    }
    res.ret = [];
    for(var i=0;i<list.length;i++) {
      res.ret.push(list[i]);
    }
    if (list.length==0) {
      self.end(res);
      return;
    }
    var pending = list.length;
    list.forEach(function(projName) {
      var dir = path.resolve(dirRoot, projName);
      fs.stat(dir, function(err, stat) {
        if (stat && stat.isDirectory()) {
          if(['sys','system','dev'].contains(projName)) res.ret.remove(projName);
        } else {
          res.ret.remove(projName);
        }
        if (!--pending) {
          res.ret.sort();
          self.end(res);
          return;
        }
      });
    });
  });
};