var Service = require('../../../../common/Service');
var utils = require('../../../../common/utils');
var Dao = require('../../dao/user_viewer');
var util = require('util');

/**
 * 创建用户查看者
 */
var AddViewer = function () {
  Service.call(this);
  this.viewers = [];
  this.curViewerIndex = 0;
  this.dao = new Dao(this);
};

util.inherits(AddViewer, Service);

module.exports = AddViewer;

/**
 * 处理服务请求
 * @param {Object} req 服务请求对象
 * @param {Object} res 服务响应对象
 */
AddViewer.prototype.process = function (req, res) {
  if (!req.userId) {
    this.onLogicError(1, '请提供用户编号！');
    return;
  }

  if (!req.viewerType) {
    this.onLogicError(2, '请提供查看者类别！');
    return;
  }

  if (!req.viewerId) {
    this.onLogicError(3, '请提供查看者编号！');
    return;
  }

  this.viewers = req.viewerId.split(',');

  var self = this;
  this.dao.delete('org_id=' + req.session.orgId + ' and user_id=' + req.userId +
    ' and viewer_type="' + req.viewerType + '" and viewer_id in (' + req.viewerId + ')',
    function () {
      self.addViewer(req, res);
    });
};

AddViewer.prototype.addViewer = function (req, res) {
  var viewerId = parseInt(this.viewers[this.curViewerIndex]);
  this.curViewerIndex++;
  var self = this;
  this.dao.create({
    org_id: req.session.orgId,
    user_id: req.userId,
    viewer_type: req.viewerType,
    viewer_id: viewerId
  }, function (ret) {
    if (self.curViewerIndex >= self.viewers.length) {
      self.emit('end', res);
    } else {
      self.addViewer(req, res);
    }
  });
};