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

/**
 * 创建数据删除服务
 */
var CreateDataDeleteTBS = function() { 
  Service.call(this);
};

util.inherits(CreateDataDeleteTBS, Service);

module.exports = CreateDataDeleteTBS;

/**
 * 处理服务请求
 * @param  {Object} req 服务请求对象
 * @param  {Object} res 服务响应对象
 */
CreateDataDeleteTBS.prototype.process =  function(req, res) {
  if(!req.path) {
    this.onLogicError(1, '请提供服务路径！');
    return;
  }
  if(!req.type) {
    this.onLogicError(2, '请提供服务类型！');
    return;
  }
  if(!req.model) {
    this.onLogicError(3, '请提供数据模型名称！');
    return;
  }
  if(!req.where) {
    this.onLogicError(5, '请设置修改条件！');
    return;
  }
  var filePath = utils.getPath(req.path);
  if(fs.existsSync(filePath)) {
    this.onLogicError(6, '文件已存在！');
    return;
  }
  var reqArgs = [];
  //解析where条件里的请求参数
  let whereTmp = req.where;
  var patt = new RegExp("{req.\\S+}", "g");
  var result = patt.exec(whereTmp);
  while (result != null)  {
    let argWhere = result[0];
    argWhere = argWhere.substring(5, argWhere.length-1);
    let isExists = false;
    for(var i=0;i<reqArgs.length;i++) {
      if(reqArgs[i].name==argWhere) {
        isExists = true;
        break;
      }
    }
    if(!isExists) reqArgs.push({
      name: argWhere,
      type: "string",
      notNull: true
    });
    whereTmp = whereTmp.replace("{req."+argWhere+"}", "");
    result = patt.exec(whereTmp);
  }
  let tbsName = req.path.substr(req.path.lastIndexOf("/")+1);
  tbsName = tbsName.substr(0, tbsName.lastIndexOf("."));
  tbsName = tbsName.substr(0, 1).toUpperCase()+tbsName.substr(1);
  var tbs = {
    name: tbsName,
    comment: "删除"+req.model,
    reqArgs: reqArgs,
    methods: [{
      name: "process",
      comment: "处理服务请求",
      args: [{
        name: "req",
        type: "object",
        comment: "服务请求对象"
      },{
        name: "res",
        type: "object",
        comment: "服务响应对象"
      }],
      statements: [{ 
        category: "db",
        type: "delete",
        model: {
          name: req.model,
          path: "/app/"+req.proj+"/model/"+req.model+".tdm"
        },
        where: req.where,
        statements: [{
          category: "common",
          type: "end"
        }]
      }]
    }]
  };

  if(req.type=="tbs") {
    fs.writeFileSync(filePath, JSON.stringify(tbs, null, "\t"));
    this.end(res);
  } else {
    var self = this;
    var compiler = new TBSCompiler();
    compiler.process({tbs: tbs}, {code: 0}, function(res2) {
      if(res2.code!=0) {
        self.onLogicError(6, "TBS文件编译失败："+res2.message);
        return;
      }
      fs.writeFileSync(filePath, res2.jsCode);
      self.end(res);
    });
  }
};