
var Book = require('../models/book.js');

function list_books(req, res) {
    Book.find({}, (err, book) => {
        if (err) {
            return res.status(500).send({ message: 'Error: Could not get books!' });
        }
        res.status(200).send({ book });
    })
}

function show_book(req, res) {
    let id = { '_id': req.params.id };
    Book.find(id, (err, book) => {
        if (err) {
            return res.status(500).send({ message: 'Error: Could not get books!' });
        }
        res.status(200).send({ book });
    })
}

function new_book(req, res) {
    try{
        let book = new Book();
        book.nombre = req.body.nombre;
        book.anio = req.body.anio;
        book.idioma = req.body.idioma;
        book.autor = req.body.autor;
        book.save((err, bookSave) => {
            if (err) {
                return res.status(400).send({ message: `Error: Could not save book to database!> ${err}` });
            }
            res.status(200).send({ book: bookSave });
        })
    } 
    catch (error) {
        res.status(500).send({ message: `error:` + error });
    }
}

function modify_book(req, res) {
    let book = new Book();
    book._id = req.params.id;
    book.nombre = req.body.nombre;
    book.anio = req.body.anio;
    book.idioma = req.body.idioma;
    book.autor = req.body.autor;
    Book.updateOne({ '_id': book._id }, book, (err, updatedBook) => {
        if (err) {
            return res.status(400).send({ message: `Error: Could not save book to database!> ${err}` });
        }
        if (updatedBook.nModified == 1) {
            res.status(200).send({ message: `Book modified!` });
        }
        else {
            res.status(400).send({ message: `Error: Book could not be modified!` });
        }
    });
}

function delete_book(req, res) {
    let id = { '_id': req.params.id };
    Book.deleteOne(id, (err, book) => {
        if (err) {
            return res.status(400).send({ message: `Error: Could not save book to database!> ${err}` });
        }
        if (book.deletedCount == 1) {
            res.status(200).send({ message: `Book deleted!` });
        }
        else {
            res.status(400).send({ message: `Error: Book could not be deleted!` });
        }
    });
}

module.exports = {
    list_books,
    show_book,
    new_book,
    modify_book,
    delete_book
};
