'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.use('/user/:id', (req, res, next) => {
  let userObject = new user(req.body)
  userObject.id = mongoose.Schema.Types.ObjectId.fromString(req.params.id)
  userObject.save(err => {
    if (err) next(err)
  })
  res.json({ status: 'ok' })
})

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

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


router.post('/animal', (req, res, next) => {
    var s1 = new species({ name: 'Introduction to Mongoose', description: "hola"});
    s1.save(function (err, spe) {
	if (err) return console.error(err);
        console.log(spe.name + " saved to bookstore collection.");
    });
})



router.use('/animal/:id', (req, res, next) => {
  let animalObject = new animal(req.body)
  animalObject.id = new mongoose.Schema.Types.ObjectId(req.params.id)
  animalObject.save(err => {
    if (err) next(err)
  })
  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}`)
})
