package v1

import (
	"encoding/json"
	"fmt"
	"git.mowie.cc/konrad/Library/models"
	"github.com/labstack/echo"
	"net/http"
	"strings"
)

type bookPayload struct {
	Book models.Book `json:"book" form:"book"`
}

// BookAdd is the handler to add a book
func BookAdd(c echo.Context) error {
	// Check for Request Content
	bookFromString := c.FormValue("book")
	var bookToInsert models.Book

	if bookFromString == "" {
		b := new(bookPayload)
		if err := c.Bind(b); err != nil {
			fmt.Println(err)
			return c.JSON(http.StatusBadRequest, models.Message{"No book model provided"})
		}
		bookToInsert = b.Book
	} else {
		// Decode the JSON
		dec := json.NewDecoder(strings.NewReader(bookFromString))
		err := dec.Decode(&bookToInsert)

		if err != nil {
			return c.JSON(http.StatusInternalServerError, models.Message{"Error decoding book: " + err.Error()})
		}
	}

	// Insert the book
	newBook, err := models.AddOrUpdateBook(bookToInsert)

	if err != nil {
		return c.JSON(http.StatusInternalServerError, models.Message{"Error"})
	}

	return c.JSON(http.StatusOK, newBook)
}
