package v1

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

// AuthorAddOrUpdate is the handler to add or update an author
func AuthorAddOrUpdate(c echo.Context) error {
	// Check for Request Content
	authorFromString := c.FormValue("author")
	var datAuthor *models.Author

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

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

	// Check if we have at least a Lastname
	if datAuthor.Lastname == "" && datAuthor.Forename == "" {
		return c.JSON(http.StatusBadRequest, models.Message{"Please provide at least one name."})
	}

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

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

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

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

	// Insert or update the author
	newAuthor, err := models.AddOrUpdateAuthor(*datAuthor)

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

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

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