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

/**
 * 设置数据库信息
 */
var SetDBInfo = function() { 
  Service.call(this);
};

util.inherits(SetDBInfo, Service);

module.exports = SetDBInfo;

/**
 * 处理服务请求
 * @param  {Object} req 服务请求对象
 * @param  {Object} res 服务响应对象
 */
SetDBInfo.prototype.process =  function(req, res) { 
	if(!req.host) {
    this.onLogicError(1, '请提供数据库服务器地址！', req, res);
    return;
  }
  if(!req.database) {
    this.onLogicError(2, '请提供数据库名称！', req, res);
    return;
  }
  if(!req.user) {
    this.onLogicError(3, '请提供数据库用户名！', req, res);
    return;
  }
  if(!req.password) {
    this.onLogicError(4, '请提供数据库密码！', req, res);
    return;
  }
  if(!req.connectTimeout) {
    this.onLogicError(5, '请提供连接超时时间！', req, res);
    return;
  }
  if(!utils.isInt(req.connectTimeout) || parseInt(req.connectTimeout)<=0) {
    this.onLogicError(6, '请提供正确的连接超时时间！', req, res);
    return;
  }
  server.config.Database.host = req.host;
  server.config.Database.database = req.database;
  server.config.Database.user = req.user;
  server.config.Database.password = req.password;
  server.config.Database.connectTimeout= req.connectTimeout*1000;
  
  utils.saveJSONToFile(utils.getPath('/config/'+server.id+'.json'), server.config);

  this.end(res);
};
