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

/**
 * 创建数据访问文件
 */
var CreateDao = function() { 
  Service.call(this);
};

util.inherits(CreateDao, Service);

module.exports = CreateDao;

/**
 * 处理服务请求
 * @param  {Object} req 服务请求对象
 * @param  {Object} res 服务响应对象
 */
CreateDao.prototype.process =  function(req, res) {
  if(!req.tableName) {
    this.onLogicError(3, '请提供数据对象名称！');
    return;
  }
  if(!req.path) {
    this.onLogicError(2, '请提供保存路径！');
    return;
  }
  this.createDaoFile(req, res);
};

CreateDao.prototype.createDaoFile = function(req, res) {
  var projName = req.path.split("/")[2];
  var className = req.tableName.substr(0,1).toUpperCase()+req.tableName.substr(1);
  var str = 'var util = require(\'util\');\r\n'
    +'var Dao = require(\'Dao\');\r\n'
    +'\r\n'
    +'var '+className+' = function(service) {\r\n'
    +'  Dao.call(this, service, \''+projName+'\', \''+req.tableName+'\');\r\n'
    +'};\r\n'
    +'\r\n'
    +'util.inherits('+className+', Dao);\r\n'
    +'\r\n'
    +'module.exports = '+className+';';
  
  var filePath = utils.getPath(req.path+'/'+req.tableName+'.js');
  if(fs.existsSync(filePath)) {
    fs.unlinkSync(filePath);
  }
  fs.writeFileSync(filePath,str);
  this.end(res);
};