package v1

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

// PublisherAddOrUpdate is the handler to add a publisher
func PublisherAddOrUpdate(c echo.Context) error {
	// Check for Request Content
	publisherFromString := c.FormValue("publisher")
	var datPublisher *models.Publisher

	if publisherFromString == "" {
		// b := new(models.Publisher)
		if err := c.Bind(&datPublisher); err != nil {
			return c.JSON(http.StatusBadRequest, models.Message{"No publisher model provided."})
		}
	} else {
		// Decode the JSON
		dec := json.NewDecoder(strings.NewReader(publisherFromString))
		err := dec.Decode(&datPublisher)

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

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

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

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

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

	// Insert or update the publisher
	newPublisher, err := models.AddOrUpdatePublisher(*datPublisher)

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

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

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