package view

import (
	"net/http"

	"xengineering.eu/ceres/model"
)

func RecipeRead(db *model.DB) func(http.ResponseWriter, *http.Request) {
	return func(w http.ResponseWriter, r *http.Request) {
		recipe := model.Recipe{}
		recipe.Id = r.PathValue("id")

		var obj model.Object = &recipe
		err := db.Transaction(obj.Read)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		template := "recipe"
		view, ok := r.URL.Query()["view"]
		if ok {
			if len(view) > 1 {
				http.Error(w, "More than one 'view' parameter given in URL", http.StatusBadRequest)
				return
			}
			template = view[0]
		}

		is_valid := false
		valid_templates := []string{
			"recipe",
			"recipe-edit",
			"recipe-confirm-deletion",
		}
		for _, v := range valid_templates {
			if template == v {
				is_valid = true
			}
		}
		if !is_valid {
			http.Error(w, "Unsupported view: "+template, http.StatusBadRequest)
			return
		}

		err = html.ExecuteTemplate(w, template, recipe)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	}
}

func RecipeCreate(w http.ResponseWriter, r *http.Request) {
	recipe := model.Recipe{}

	err := html.ExecuteTemplate(w, "recipe-edit", recipe)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
}