'use strict';

/**
 * Module dependencies.
 */
var path = require('path'),
  mongoose = require('mongoose'),
  Person = mongoose.model('Person'),
  errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller')),
  _ = require('lodash');

/**
 * Create a Person
 */
exports.create = function(req, res) {
  var person = new Person(req.body);
  person.user = req.user;

  person.save(function(err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(person);
    }
  });
};

/**
 * Show the current Person
 */
exports.read = function(req, res) {
  // convert mongoose document to JSON
  var person = req.person ? req.person.toJSON() : {};

  // Add a custom field to the Article, for determining if the current User is the "owner".
  // NOTE: This field is NOT persisted to the database, since it doesn't exist in the Article model.
  // person.isCurrentUserOwner = req.user && person.user && person.user._id.toString() === req.user._id.toString();

  res.jsonp(person);
};

/**
 * Update a Person
 */
exports.update = function(req, res) {
  var person = req.person;

  person = _.extend(person, req.body);

  person.save(function(err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(person);
    }
  });
};

/**
 * Delete a Person
 */
exports.delete = function(req, res) {
  var person = req.person;

  person.remove(function(err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(person);
    }
  });
};

/**
 * List of People
 */
exports.list = function(req, res) {
  var search = {};
  if (req.query.full_name) {
    search.full_name = new RegExp(req.query.full_name, 'i');
  }
  if (req.query.url) {
    search.url = new RegExp(req.query.url, 'i');
  }
  if (req.query.email) {
    search.email = new RegExp(req.query.email, 'i');
  }
  if (req.query.job) {
    search.job = new RegExp(req.query.job, 'i');
  }
  if (req.query.location_safe) {
    search.location_safe = new RegExp(req.query.location_safe, 'i');
  }
  if (req.query.phone) {
    search.phone = new RegExp(req.query.phone, 'i');
  }
  if (req.query.notes) {
    search.notes = new RegExp(req.query.notes, 'i');
  }
  if (req.query.keywords) {
    search.keywords = new RegExp(req.query.keywords, 'i');
  }

  Person.find(search).sort('-created').exec(function (err, people) {
    if (err) {
      return res.status(400).send({
        message: err.message
      });
    } else {
      res.json(people);
    }
  });
};

/**
 * List of Dupliacte People
 */
exports.duplicates = function (req, res) {

  var aggregate = [
    {
      $group: {
        _id: { url: '$url' },
        count: { $sum: 1 }
      }
    }, {
      $match: {
        count: { $gte: 2 }
      }
    }
  ];

  Person.aggregate(aggregate, function (err, groups) {

    if (err) {
      return res.status(400).send({
        message: err.message
      });

    } else {
      var dup_urls = [];
      for (var i = 0; i < groups.length; i++) {
        var group = groups[i];
        var _id = group._id;
        dup_urls.push(_id.url);
      }

      Person.find({ url: { $in: dup_urls } }).sort('url').exec(function (err, people) {
        if (err) {
          return res.status(400).send({
            message: err.message
          });
        } else {
          res.json(people);
        }
      });

    }

  });

};

/**
 * Person middleware
 */
exports.personByID = function(req, res, next, id) {

  if (!mongoose.Types.ObjectId.isValid(id)) {
    return res.status(400).send({
      message: 'Person is invalid'
    });
  }

  Person.findById(id).populate('user', 'displayName').exec(function (err, person) {
    if (err) {
      return next(err);
    } else if (!person) {
      return res.status(404).send({
        message: 'No Person with that identifier has been found'
      });
    }
    req.person = person;
    next();
  });
};

