package v1

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

// PublisherAdd is the handler to add a publisher
func PublisherAdd(c echo.Context) error {
	// Check for Request Content
	publisher := c.FormValue("publisher")
	if publisher == "" {
		return c.JSON(http.StatusBadRequest, models.Message{"No publisher model provided"})
	}

	// Decode the JSON
	var publisherstruct models.Publisher
	dec := json.NewDecoder(strings.NewReader(publisher))

	err := dec.Decode(&publisherstruct)
	if err != nil {
		return c.JSON(http.StatusInternalServerError, models.Message{"Error decoding publisher: " + err.Error()})
	}

	// Insert the publisher
	newPublisher, err := models.AddPublisher(publisherstruct)

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

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