package view

import (
	"net/http"

	"xengineering.eu/ceres/model"

	"github.com/gorilla/mux"
)

func Recipe(w http.ResponseWriter, r *http.Request) {
	recipe := model.Recipe{}
	recipe.Id = mux.Vars(r)[`id`]

	err := recipe.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",
	}
	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
	}
}