package fr.unice.iut.library.services;

import fr.unice.iut.library.Book;
import fr.unice.iut.library.Library;
import fr.unice.iut.library.exceptions.BookAlreadyExistException;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import java.util.List;

@Path("/book")
public class LibraryServiceImpl implements LibraryService {

    @Override
    public List<Book> getAllBooks() {
        return Library.getAllBooks();
    }

    @Override
    public Response getBook(String isbn) {
        Book b = Library.retrieveBookByISBN(isbn);
        if (b == null) {
            return Response.status(Response.Status.NOT_FOUND).build();
        }
        return Response.ok(b).build();
    }

    @Override
    public Response createBook(String bookJSON) {
        JSONObject book = null;
        try {
            book = new JSONObject(bookJSON);
            String isbn = book.optString("isbn");
            String title = book.optString("title");
            Library.createBook(new Book(isbn,title));
            return Response.ok().build();
        } catch (BookAlreadyExistException e) {
            return Response.status(500).entity("This book already exist.").build();
        } catch (JSONException e) {
            return Response.status(400).entity("Invalid input.").build();
        }
    }
}
