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

/**
 * 设置日志信息
 */
var SetLogInfo = function() { 
  Service.call(this);
};

util.inherits(SetLogInfo, Service);

module.exports = SetLogInfo;

/**
 * 处理服务请求
 * @param  {Object} req 服务请求对象
 * @param  {Object} res 服务响应对象
 */
SetLogInfo.prototype.process =  function(req, res) { 
  if(!req.logFileSavePath) {
    this.onLogicError(1, '请提供日志文件保存路径！', req, res);
    return;
  }
  if(!req.logFileSaveDays) {
    this.onLogicError(2, '请提供日志文件保留时长！', req, res);
    return;
  }
  if(!utils.isInt(req.logFileSaveDays) || parseInt(req.logFileSaveDays)<=0) {
    this.onLogicError(3, '请提供正确的日志文件保留时长！', req, res);
    return;
  }
  if(!req.clearTime) {
    this.onLogicError(4, '请提供每天清除日志时间！', req, res);
    return;
  }
  if(req.clearTime.length!=5 || req.clearTime.indexOf(':')!=2 
    || req.clearTime.split(':').length!=2) {
    this.onLogicError(5, '请提供正确的清除日志时间！', req, res);
    return;
  }
  if(!req.saveDays) {
    this.onLogicError(6, '请提供数据库日志记录保留时长！', req, res);
    return;
  }
  if(!utils.isInt(req.saveDays) || parseInt(req.saveDays)<=0) {
    this.onLogicError(7, '请提供正确的数据库日志记录保留时长！', req, res);
    return;
  }

  server.config.Logger.logFileSavePath = req.logFileSavePath;
  server.config.Logger.logFileSaveDays = req.logFileSaveDays;
  server.config.Logger.clearTime = req.clearTime;
  server.config.Logger.outputToConsole = false;
  if(req.outputToConsole) server.config.Logger.outputToConsole = true;
  server.config.Logger.logRequestHeader = false;
  if(req.logRequestHeader) server.config.Logger.logRequestHeader = true;
  server.config.Logger.logRequestData = false;
  if(req.logRequestData) server.config.Logger.logRequestData = true;
  server.config.Logger.logResponseData = false;
  if(req.logResponseData) server.config.Logger.logResponseData = true;
  
  server.config.Logger.saveToDB.saveDays = req.saveDays;
  server.config.Logger.saveToDB.logRequest = false;
  if(req.logRequest) server.config.Logger.saveToDB.logRequest = true;
  server.config.Logger.saveToDB.logStatic = false;
  if(req.logStatic) server.config.Logger.saveToDB.logStatic = true;
  server.config.Logger.saveToDB.logService = false;
  if(req.logService) server.config.Logger.saveToDB.logService = true;
  server.config.Logger.saveToDB.logUpload = false;
  if(req.logUpload) server.config.Logger.saveToDB.logUpload = true;
  server.config.Logger.saveToDB.logDownload = false;
  if(req.logDownload) server.config.Logger.saveToDB.logDownload = true;
  server.config.Logger.saveToDB.logSql = false;
  if(req.logSql) server.config.Logger.saveToDB.logSql = true;
  server.config.Logger.saveToDB.logError = false;
  if(req.logError) server.config.Logger.saveToDB.logError = true;
  
  logger.setConfig(server.config.Logger);
  
  utils.saveJSONToFile(utils.getPath('/config/'+server.id+'.json'), server.config);
  
  this.end(res);
};
