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

/**
 * 上传文件
 */
var UploadFile = function() { 
  Service.call(this);
  this.sqlInject.exclude = ['dir', 'fileName'];
};

util.inherits(UploadFile, Service);

module.exports = UploadFile;

/**
 * 处理服务请求
 * @param  {Object} req 服务请求对象
 * @param  {Object} res 服务响应对象
 */
UploadFile.prototype.process =  function(req, res) {
  if(!req.fileCode && !req.fileContent) {
    this.onLogicError(1, '请提供文件代码或内容！');
    return;
  }
  if(!req.dir) {
    this.onLogicError(2, '请提供保存路径！');
    return;
  }
  if(!req.fileName) {
    this.onLogicError(3, '请提供保存路径！');
    return;
  }
  var self = this;
  var savePath = utils.getPath(req.dir+"/"+decodeURIComponent(req.fileName));
  if(fs.existsSync(savePath)) {
    try {
      fs.unlinkSync(savePath);
    } catch(err) {
      self.onLogicError(4, '删除文件失败！');
      return;
    }
  }
  if(req.fileCode) {
    var tmpPath = server.attachSavePath+'/tmp/upload_'+req.fileCode;
    fs.rename(utils.formatPath(tmpPath), savePath, function() {
      self.end(res);
    });
  } else {
    fs.writeFile(savePath,req.fileContent,function(err) {
      if(err) {
        res.code = 3;
        res.message = err.message;
        console.log(err.message);
      }
      self.end(res);
    });
  }
};