package v1

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

// 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 == "" {
		if err := c.Bind(&datItem); err != nil {
			return c.JSON(http.StatusBadRequest, models.Message{"No item model provided."})
		}
	} else {
		// Decode the JSON
		dec := json.NewDecoder(strings.NewReader(itemFromString))
		err := dec.Decode(&datItem)

		if err != nil {
			return c.JSON(http.StatusBadRequest, 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
	}

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

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

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

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

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

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