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 CreateModel = function() { 
  Service.call(this);
};

util.inherits(CreateModel, Service);

module.exports = CreateModel;

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

CreateModel.prototype.createModelFile = function(req, res) {
  var self = this;
  var dao = new Dao(this);
  dao.execute('select table_type from information_schema.TABLES '
    +'where table_schema="'+server.config.Database.database
    +'" and table_name="'+req.tableName+'"', null, function(rows1) {
    if(rows1.length==0) {
      self.onLogicError(4, '数据对象不存在！');
      return;
    }
    let tableType = "table";
    if(rows1[0].table_type=="VIEW") tableType = "view";
    dao.execute('select column_name,column_default,column_key,is_nullable,extra,'
      +'data_type,character_maximum_length,numeric_precision,numeric_scale,column_comment '
      +'from information_schema.COLUMNS where table_schema="'
      +server.config.Database.database+'" and table_name="'+req.tableName
      +'"', null, function(rows) {
      var str = '{\r\n'
        +'    "table" : "'+req.tableName+'",\r\n'
        +'    "type" : "'+tableType+'",\r\n'
        +'    "fields" : \r\n'
        +'    {\r\n';
      let fieldOrders = "";
      for(var i=0;i<rows.length;i++) {
        if(fieldOrders!="") fieldOrders += ',';
        fieldOrders += '"'+rows[i].column_name+'"';
        var dataType = rows[i].data_type;
        str += '        "'+rows[i].column_name+'" : {"dataType": "'
          +dataType.toUpperCase()+'", "type" : ';
        if(dataType=='int'||dataType=='smallint'||dataType=='bigint'
          ||dataType=='mediumint'||dataType=='tinyint') {
          str += '"int"';
          if(rows[i].extra=='auto_increment') str += ', "autoIncrement" : true';
        } else if(dataType=='datetime'||dataType=='date'||dataType=='time') {
          str += '"datetime"';
        } else if(dataType=='decimal') {
          str += '"numeric", "length": '+rows[i].numeric_precision+', "precision": '+rows[i].numeric_scale;
        } else {
          str += '"string", "length": '+rows[i].character_maximum_length;
        }
        if(rows[i].column_key=='PRI') str += ', "primaryKey" : true';
        if(rows[i].is_nullable=='NO') str += ', "notNull" : true';
        if(rows[i].column_default) {
          if(["VARCHAR","CHAR","TEXT","DATETIME","DATE","TIME"].contains(dataType.toUpperCase())) {
            str += ', "default" : "'+rows[i].column_default+'"';
          } else {
            str += ', "default" : '+rows[i].column_default;
          }
        }
        if(rows[i].column_comment) str += ', "comment" : "'+rows[i].column_comment+'"';
        str += '}';
        if(i<rows.length-1) str += ',';
        str += '\r\n';
      }
      str += '    },\r\n';
      str += '    "indexs" : ['+fieldOrders+']\r\n';
      str += '}';
      var filePath = utils.getPath(req.path+'/'+req.tableName+'.tdm');
      if(fs.existsSync(filePath)) {
        fs.unlinkSync(filePath);
      }
      fs.writeFileSync(filePath,str);
      if(req.returnContent) res.data = str;
      self.end(res);
      //self.createDaoFile(req, res);
    });
  });
};

CreateModel.prototype.createDaoFile = function(req, res) {
  var projName = req.path.split("/")[2];
  var className = req.tableName.substr(0,1).toUpperCase()+name.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 = path.normalize(req.path+'/dao/'+req.tableName+'.js');
  if(fs.existsSync(filePath)) {
    fs.unlinkSync(filePath);
  }
  fs.writeFileSync(filePath,str);
  this.end(res);
};