/**
 * Created by Stein-Otto Svorstøl on 26.08.15.
 * Logic of book requests
 */

var Books = require('../models/book');

module.exports = {
    createNew: function(req, res){
        var book = req.body;
        delete book._id; // Getting a -1 from clients
        if(!isValidBookObject(book)) return res.sendStatus(422); // Unprocessable
        Books.findWithISBNAndOwner(book.isbn, book.owner, function(result){ // see if it's already there
            // @todo update if already there
            Books.insert(book, function(result){ // Not there, so it can be created
                res.json(result);
            });
        });
    },

    getWithISBN: function(req, res){
        var isbn = req.params.isbn;
        Books.findWithISBN(isbn, function(result){
            if (result === 404){
                return res.sendStatus(404);  // not found
            }
            res.json(result);
        });
    },

    getBooksOfOwner: function (req, res){
        var owner = req.params.owner;
        Books.findWithOwner(owner, function(result){
            if (result === 404) return res.sendStatus(404); 
            res.json(result);
        });
    },

    getWithISBNAndOwner: function(req, res){
        var isbn = req.params.isbn;
        var owner = req.params.owner;
        Books.findWithISBNAndOwner(isbn, owner, function(result){
            if (result === 404) return res.sendStatus(404);
            res.json(result);
        });
    },



    addRenter: function(req, res){
        Books.addRenter(req.params.isbn, req.params.owner, req.params.renter, function(result){
            res.json(result);
        });
    },

    removeRenter: function(req, res){
        Books.removeRenter(req.params.isbn, req.params.owner, req.params.renter, function(result){
            res.json(result);
        });
    }
};

function isValidBookObject(book){
    if (book.isbn && book.owner && book.rentedTo
        && book.numAvailableForRent && book.numberOfCopies
        && Object.keys(book).length === 5) return true;
    return false;
}
@@ -455,40 +455,89 @@
     
-// @todo update if already there
+if (result !== 404)%7B // Something was found, so we'll update item.%0A%0A            %7D
 %0A   
@@ -1919,16 +1919,23 @@
     if (
+typeof 
 book.isb
@@ -1940,38 +1940,118 @@
 sbn 
-&& book.owner && book.rentedTo
+=== 'string' && typeof book.owner === 'string'%0A        && typeof book.rentedTo === 'object' // Should be array
 %0A   
@@ -2057,16 +2057,23 @@
       &&
+ typeof
  book.nu
@@ -2090,18 +2090,46 @@
 ForRent 
-&&
+=== 'number'%0A        && typeof
  book.nu
@@ -2140,16 +2140,29 @@
 OfCopies
+ === 'number'
 %0A       

Add more extensive book validation: Check attribute naems, types, and number of values