package controller

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"time"

	"xengineering.eu/ceres/model"

	"github.com/gorilla/mux"
)

func RecipeCreate(w http.ResponseWriter, r *http.Request) {
	recipe := model.Recipe{}
	recipe.Title = "recipe without title"
	recipe.LastChanged = fmt.Sprint(time.Now().Unix())
	recipe.Created = recipe.LastChanged

	tx, err := model.NewTx()
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	err = recipe.Create(tx)
	if err != nil {
		model.Rollback(tx)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	err = tx.Commit()
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	http.Redirect(w, r, "/recipe/"+recipe.Id+"?view=recipe-edit", http.StatusSeeOther)
}

func RecipeUpdate(w http.ResponseWriter, r *http.Request) {
	buf, err := io.ReadAll(r.Body)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	recipe := model.Recipe{}
	err = json.Unmarshal(buf, &recipe)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	if recipe.Id != mux.Vars(r)[`id`] {
		http.Error(w, "IDs in URL and JSON do not match", http.StatusBadRequest)
		return
	}

	recipe.LastChanged = fmt.Sprint(time.Now().Unix())

	tx, err := model.NewTx()
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	err = recipe.Update(tx)
	if err != nil {
		model.Rollback(tx)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	err = tx.Commit()
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	http.Redirect(w, r, "/recipe/"+recipe.Id, http.StatusSeeOther)
}

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

	tx, err := model.NewTx()
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	err = recipe.Delete(tx)
	if err != nil {
		model.Rollback(tx)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	err = tx.Commit()
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	http.Redirect(w, r, "/recipes", http.StatusSeeOther)
}