package v1

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

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

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

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

	// Check if we have an ID other than the one in the struct
	id := c.Param("id")
	if id != "" {
		// Make int
		bookID, err := strconv.ParseInt(id, 10, 64)

		if err != nil {
			return c.JSON(http.StatusInternalServerError, models.Message{"Could not get book id."})
		}
		datBook.ID = bookID
	}

	// Check if the book exists
	if datBook.ID != 0 {
		_, exists, err := models.GetBookByID(datBook.ID)
		if err != nil {
			return c.JSON(http.StatusInternalServerError, models.Message{"Could not check if the book exists."})
		}

		if !exists {
			return c.JSON(http.StatusNotFound, models.Message{"The book does not exist."})
		}
	}

	// Check if we have at least a title
	if datBook.Title == "" && datBook.ID == 0 {
		return c.JSON(http.StatusBadRequest, models.Message{"You need at least a title to insert a new book!"})
	}

	// Insert or update the book
	newBook, err := models.AddOrUpdateBook(*datBook)

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

	// Log the action
	err = models.LogAction("Added or updated a book", newBook.ID, c)
	if err != nil {
		return c.JSON(http.StatusInternalServerError, models.Message{"Could not log."})
	}

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