package v1

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

type itemPayload struct {
	Item models.Item `json:"item" form:"item"`
}

// ItemAddOrUpdate is the handler to add a item
func ItemAddOrUpdate(c echo.Context) error {
	// Check for Request Content
	itemFromString := c.FormValue("item")
	var datItem models.Item

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

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

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

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

	// Insert or update the item
	newItem, err := models.AddOrUpdateItem(datItem)

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

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