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

/**
 * 添加
 */
var Add = function() { 
  Service.call(this);
};

util.inherits(Add, Service);

module.exports = Add;

/**
 * 处理服务请求
 * @param  {Object} req 服务请求对象
 * @param  {Object} res 服务响应对象
 */
Add.prototype.process =  function(req, res) {
  if(!req.id) {
    this.onLogicError(1, '请提供服务ID！');
    return;
  }
  if(!req.name) {
    this.onLogicError(2, '请提供服务名称！');
    return;
  }
  if(!req.path) {
    this.onLogicError(3, '请提供服务路径！');
    return;
  }
  console.log(utils.appendPath('/app', req.path));
  var servicePath = utils.getPath(utils.appendPath('/app', req.path));
  console.log(servicePath);
  if(!fs.existsSync(servicePath)) {
    this.onLogicError(4, '请提供正确的服务路径！');
    return;
  }
  for(sid in server.bgServices) {
    var service = server.bgServices[sid];
    if(service.id==req.id || service.name==req.name || service.path==req.path) {
      this.onLogicError(5, '服务ID、名称或路径已经存在！');
      return;
    }
  }
  var BackgroundService = server.loadModule(utils.appendPath('/app', req.path));
  var bgService = new BackgroundService();
  bgService.id = req.id;
  bgService.path = req.path;
  bgService.name = req.name;
  bgService.isRunning = false;
  server.bgServices[bgService.id] = bgService;

  server.config.BackgroundServices.push({
    id: bgService.id,
    name: bgService.name,
    path: bgService.path
  });

  utils.saveJSONToFile(utils.getPath('/config/'+server.id+'.json'), server.config);

  this.end(res);
};