var Service = require('Service');
var util = require('util');
var RequestDao = require('../../dao/log_request');
var SessionDao = require('../../dao/log_session');
var DownloadDao = require('../../dao/log_download');
var ErrorDao = require('../../dao/log_error');
var DbDao = require('../../dao/log_db');

/**
 * 获得日志列表
 */
var GetUpload = function() { 
  Service.call(this);
};

util.inherits(GetUpload, Service);

module.exports = GetUpload;

/**
 * 处理服务请求
 * @param  {Object} req 服务请求对象
 * @param  {Object} res 服务响应对象
 */
GetUpload.prototype.process =  function(req, res) {
  if(!req.id) {
    this.onLogicError(1, '请提供日志编号！');
    return;
  }
  var self = this;
  var dao = new DownloadDao(this);
  dao.query({where:'id='+req.id}, function(rows){
  	if(rows.length==0) {
  	  self.onLogicError(2, '请提供正确的日志编号！');
      return;
  	}
  	res.log = rows[0];
  	var dbDao = new DbDao(self);
	dbDao.query({where:'request_id='+res.log.id}, function(rowsDb) {
	  res.dbLog = rowsDb;
	    var errorDao = new ErrorDao(self);
	    errorDao.query({where:'request_id='+res.log.id}, function(rowsError) {
	  	  res.errorLog = rowsError;
	  	  var reqDao = new RequestDao(self);
	  	  reqDao.query({where: 'id='+res.log.id}, function(rowsReq) {
	  	  	if(rowsReq.length>0) res.req = rowsReq[0];
		  	if(res.log.session_id) {
		      var sessionDao = new SessionDao(self);
		      sessionDao.query({where: 'id='+res.log.session_id}, function(rowsSession) {
		      	if(rowsSession.length>0) res.session = rowsSession[0];
		      	self.emit('end', res);
		      });
		  	} else {
		      self.emit('end', res);
		    }
	  	  });
	    });
	});
  });
};