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

/**
 * 检查文件路径
 */
var CheckFilePath = function() { 
  Service.call(this);
};

util.inherits(CheckFilePath, Service);

module.exports = CheckFilePath;

/**
 * 处理服务请求
 * @param  {Object} req 服务请求对象
 * @param  {Object} res 服务响应对象
 */
CheckFilePath.prototype.process =  function(req, res) {
  if(!req.path) {
    this.onLogicError(1, "请提供路径！");
    return;
  }
  if(!req.name) {
    this.onLogicError(2, "请提供文件名称！");
    return;
  }
  if(req.name.match(/[^\w]/g)) {
    this.onLogicError(3, "文件名称只能包含字母、数字或下划线！");
    return;
  }
  if(!req.type) {
    this.onLogicError(4, "请提供文件类型！");
    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(5, "文件已存在！");
    return;
  }
  this.end(res);
};