
var express = require('express')
var cors = require('cors')
// bodyParser is a lib that parses POST & PUT data
var bodyParser = require('body-parser')

// add some entities
var people = require("./people/people.js")

var app = express()
var port = process.env.PORT || 8080;

app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.use(cors())


function end(res,err) {
  if (err) {
    res.status(500).send(err)
  }else{
    res.send("ok")
  }
}

var people_path = '/people'

app.get(people_path,function (req,res) {
  people.index(function (err,people) {
    res.send(people)
  })
})

app.post(people_path,function (req,res) {
  var person_name = req.body.name
  people.create(person_name, function (err) {
    end(res,err)
  })
})

app.put(people_path,function (req,res) {
  people.modify(req.body.person_id,req.body.name,  function (err) {
    end(res,err)
  })
})

app.delete(people_path+"/:person_id/pets/:petname",function (req,res) {
  people.removePet(req.params.person_id,req.params.petname, function (err) {
    end(res,err)
  })
})

app.delete(people_path+"/:person_id",function (req,res) {
  people.remove(req.params.person_id,  function (err) {
    end(res,err)
  })
})

app.post(people_path+"/pets",function (req,res) {
  people.addPet(req.body.person_id,req.body.petname, function (err) {
    end(res,err)
  })
})


app.listen(port)
