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

/**
 * 添加前端资源
 */
var CreateClientFile = function() { 
  Service.call(this);
};

util.inherits(CreateClientFile, Service);

module.exports = CreateClientFile;

/**
 * 处理服务请求
 * @param  {Object} req 服务请求对象
 * @param  {Object} res 服务响应对象
 */
CreateClientFile.prototype.process =  function(req, res) {
  if(!req.type) {
    this.onLogicError(1, "请提供资源类型！");
    return;
  }
	if(!req.name) {
    this.onLogicError(2, "请提供资源名称！");
    return;
  }
  if(!req.path) {
    this.onLogicError(3, "请提供路径！");
    return;
  }
  if(req.type=="dir") {
    var dir = utils.getPath(req.path+"/"+req.name);
    if(!fs.existsSync(dir)) fs.mkdirSync(dir);
    this.end(res);
    return;
  }
  let fileName = req.name.endWith("."+req.type) ? req.name : req.name+"."+req.type;
  let filePath = utils.getPath(req.path+"/"+fileName);
  if(fs.existsSync(filePath)) {
    this.onLogicError(4, "文件已存在！");
    return;
  }

	var str = '';
  if(req.type=="html") {
    str = "<html>\r\n";
    str += "<head>\r\n";
    str += "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\r\n";
    str += "<title></title>\r\n";
    str += "</head>\r\n";
    str += "<body>\r\n";
    str += "  \r\n";
    str += "</body>\r\n";
    str += "</html>\r\n";
  } else {
    str += " ";
  }
  fs.writeFileSync(filePath, str);

  this.end(res);
};