'use strict';

var mongoose = require('mongoose')
    , Query    = mongoose.Query;
function populateFunction(oldFunction){
  return function(string){
    var data = [];
    if(typeof string == "string"){
      data = data.concat(string.split(" ").map(function(arg){
        return {
          path: arg,
          match:{deleted:{$ne:true}}
        }
      }))
    }else{
      data = string;
    }
    return oldFunction.call(this, data);
  }
}
module.exports = function(schema) {

  Query.prototype.populate = populateFunction(Query.prototype.populate);

  schema.add({ deleted: Boolean });
  schema.add({ deletedAt: Date });

  schema.pre('save', function (next) {
    if (!this.deleted) {
      this.deleted = false;
    }

    if (!this.deletedAt) {
      this.deletedAt = null;
    }

    next();
  });

  schema.methods.softdelete = function(callback) {
    this.deleted = true;
    this.deletedAt = new Date();
    this.save(callback);
  };

  schema.methods.restore = function(callback) {
    this.deleted = false;
    this.deletedAt = null;
    this.save(callback);
  };


};
