package controllers

import (
	"github.com/google/uuid"
	"github.com/gorilla/mux"
	"github.com/unrolled/render"
	"moretcgshop/app/models"
	"net/http"
)

func (server *Server) Categories(w http.ResponseWriter, r *http.Request) {
	renderer := render.New(render.Options{
		Layout:     "layout",
		Extensions: []string{".html", ".tmpl"},
	})

	vars := mux.Vars(r)

	if vars["id"] == "" {
		return
	}

	game, _ := models.GetSectionByID(server.DB, vars["id"])

	categoryModel := models.Category{}

	categories, err := categoryModel.GetCategory(server.DB, vars["id"])
	user := server.CurrentUser(w, r)
	println(user)

	if err != nil {
		println(err.Error())
		return
	}

	_ = renderer.HTML(w, http.StatusOK, "categories", map[string]interface{}{

		"game":       game,
		"categories": categories,
		"user":       user,
	})
}

func (server *Server) AdminCategoryList(w http.ResponseWriter, r *http.Request) {
	renderer := render.New(render.Options{
		Layout:     "layout",
		Extensions: []string{".html", ".tmpl"},
	})

	vars := mux.Vars(r)
	if vars["spielid"] == "" {
		println("spielid is leer")
		return
	}

	section, err := models.GetSectionByID(server.DB, vars["spielid"])

	categoryModel := models.Category{}
	categories, err := categoryModel.GetCategory(server.DB, vars["spielid"])

	if err != nil {
		println(err.Error())
		return
	}

	_ = renderer.HTML(w, http.StatusOK, "admin_categoryList", map[string]interface{}{
		"categories": categories,
		"spiel":      section,
	})
}

func (server *Server) AdminCategoryPost(w http.ResponseWriter, r *http.Request) {
	kategorieName := r.FormValue("katname")
	spielID := r.FormValue("spielid")

	if kategorieName == "" {
		SetFlash(w, r, "error", "Kategoriename wurde nicht eingetragen")
		http.Redirect(w, r, "/admin/category/"+spielID, http.StatusSeeOther)
		return
	}

	kategorieModel := &models.Category{}

	params := &models.Category{
		ID:        uuid.New().String(),
		Name:      kategorieName,
		SectionID: spielID,
	}

	_, err := kategorieModel.CreateCategory(server.DB, params)
	if err != nil {
		SetFlash(w, r, "error", "Sorry das war nicht erfolgreich")
		http.Redirect(w, r, "/admin/category/"+spielID, http.StatusSeeOther)
		return
	}

	http.Redirect(w, r, "/admin/category/"+spielID, http.StatusSeeOther)

}
