'use strict';

/**
 * Module dependencies.
 */
const mongoose = require('mongoose'),
  express = require('express'),
  http = require('http'),
  bodyParser = require('body-parser'),
  methodOverride = require('method-override'),
  cookieParser = require('cookie-parser'),
  app = express(),
  router = express.Router(),
  db = mongoose.connect('mongodb://172.29.0.102:27017/familyark', { useMongoClient: true }),
  user = require('./model/user')(db),
  animal = require('./model/animal')(db),
  species = require('./model/species')(db),
  host = '172.29.0.101',
  port = 3000

http.createServer(app)

router.get('/species', (req, res, next) => {
   
    species.find({}, (err, result) => {
        if (err) next(err)
	else res.json({ data: result,  status: 'ok' })
    })
})

router.get('/animal', (req, res, next) => {
    animal.find({}, (err, result) => {
        if (err) next(err)
        else res.json({ data: result,  status: 'ok' })
    })
})

router.post('/animal', (req, res, next) => {
    let s1 = new animal(req.body)
    s1.save((err, doc) => {
	if (err) next(err)
        else res.json(doc)
    })
})

router.put('/animal/:id', (req, res, next) => {
    animal.findOneAndUpdate({_id: req.params.id}, req.body, {upsert: true}, (err, doc) => {
        if (err) next(err)
        else res.json(doc)
    })
})

router.delete('/animal/:id', (req, res, next) => {
    animal.remove({ _id: req.params.id }, function(err) {
        if (!err) next(err)
        else res.json({ status: 'ok' })
    });
})

app.use(bodyParser.urlencoded({
  extended: true
}))
.use(bodyParser.json())
.use(methodOverride())
.use(cookieParser())
.use(router)
.use(express.static('public')).listen(port, host, () => {
  console.log(`Listening on: ${host}:${port}`)
})
