package comics

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 (
	// ComicsPublisherTemplate defines name of template file for comics publishers
	ComicsPublisherTemplate = "comics/publishers.html"
	// ComicsPublisherDetailsTemplate defines name of template file for comics publishers
	ComicsPublisherDetailsTemplate = "comics/publisher.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": "Comics Publisher List", "payload": publishers}, ComicsPublisherTemplate)
	} 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": "Comics Publisher", "payload": publisher, "action": util.SaveAction}, ComicsPublisherDetailsTemplate)
	} else {
		c.AbortWithError(http.StatusNotFound, err)
	}
}

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

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, "/comics/publisher")
	} else {
		c.HTML(http.StatusBadRequest, "comics/publisher.html", gin.H{
			"ErrorTitle":   "Publisher Creation Failed",
			"ErrorMessage": err.Error()})
	}
}
