package library

import (
	"gitlab.thpeetz.de/kontor/kontor-go/pkg/dao"
	"gitlab.thpeetz.de/kontor/kontor-go/pkg/util"
	"net/http"

	"github.com/gin-gonic/gin"
)

const (
	// LibraryPublisherTemplate defines name of template file for comics publishers
	LibraryPublisherTemplate = "library/publishers.html"
)

func showPublisherList(c *gin.Context) {
	var dao = PublisherDAO{Db: dao.KontorDb}
	if publishers, err := dao.FindAll(); err == nil {
		util.Render(c, gin.H{"title": "Library Publisher List", "payload": publishers}, LibraryPublisherTemplate)
	} else {
		c.AbortWithError(http.StatusNotFound, err)
	}
}

func showPublisherDetails(c *gin.Context) {
	var dao = PublisherDAO{Db: dao.KontorDb}
	publisherid := c.Param("publisher_id")
	if publisher, err := dao.FindByID(publisherid); err == nil {
		util.Render(c, gin.H{"title": "Library Publisher", "payload": publisher, "action": util.SaveAction}, LibraryPublisherTemplate)
	} else {
		c.AbortWithError(http.StatusNotFound, err)
	}
}

func showPublisherCreation(c *gin.Context) {
	var publisher = Publisher{}
	util.Render(c, gin.H{"title": "Library Publisher Creation", "payload": publisher, "action": util.AddAction}, LibraryPublisherTemplate)
}

func validatePublisherDetails(c *gin.Context) {
	name := c.PostForm("name")
	action := c.PostForm("action")
	publisherid := c.PostForm("publisherid")

	var err error
	var dao = PublisherDAO{Db: dao.KontorDb}
	var publisher = Publisher{}

	switch action {
	case util.AddAction:
		publisher.Name = name
		_, err = dao.Upsert(publisher)
	case util.SaveAction:
		publisher, _ = dao.FindByID(publisherid)
		publisher.Name = name
		err = dao.Update(publisher)
	case util.DeleteAction:
		publisher, _ = dao.FindByID(publisherid)
		err = dao.Delete(publisher)
	}
	if err == nil {
		c.Redirect(http.StatusTemporaryRedirect, "/library/publisher")
	} else {
		c.HTML(http.StatusBadRequest, "library/publisher.html", gin.H{
			"ErrorTitle":   "Publisher Creation Failed",
			"ErrorMessage": err.Error()})
	}
}
