var db = require('../db/db.js')
var mongoose = require('mongoose')

var people = {}

db.once('open',function () {
  people.model = mongoose.model('People',{ name: String, pets: Array })

  people.index = function (callback) {
    people.model.find({},callback)
  }

  people.create = function (personName, callback) {
    var newPeople = new people.model({ name: personName })
    newPeople.save(callback)
  }

  people.modify = function (id,name,callback) {
    people.model.findById(id).then(function (person) {
      person.name = name
      person.save(callback)
    })
  }

  people.remove = function (id,callback) {
    people.model.findById(id).remove(callback)
  }

  people.addPet = function (id,pet_name,callback) {
    people.model.findById(id).then(function (person) {
      person.pets.push(pet_name)
      person.save(callback)
    })
  }

  people.removePet = function (id, pet_name , callback) {
    people.model.findById(id).then(function (person) {
      person.pets.remove(pet_name)
      person.save(callback)
    })
  }

})

module.exports = people
