package api

import (
	"net/http"

	"github.com/gorilla/mux"
	"github.com/gorilla/schema"
	"gogs.carducci-dante.gov.it/karmen/core/orm"
	"gogs.carducci-dante.gov.it/karmen/core/renderer"
)

func schoolShowHandler() http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		var (
			teachers   []orm.Teacher
			classes    []orm.Class
			subjects   []orm.Subject
			activities []orm.Activity
			data       struct {
				School          orm.School
				NumOfTeachers   int
				NumOfSubjects   int
				NumOfClasses    int
				NumOfActivities int
				Issues          []orm.Issue
			}
		)

		if !orm.DB().First(&data.School, mux.Vars(r)["id"]).RecordNotFound() {
			if err := orm.DB().First(&data.School, mux.Vars(r)["id"]).Error; err != nil {
				panic(err)
			}
		}

		if err := orm.DB().Find(&teachers).Error; err != nil {
			panic(err)
		}

		if err := orm.DB().Find(&classes).Error; err != nil {
			panic(err)
		}

		if err := orm.DB().Find(&activities).Error; err != nil {
			panic(err)
		}

		if err := orm.DB().Find(&subjects).Error; err != nil {
			panic(err)
		}

		data.NumOfTeachers = len(teachers)
		data.NumOfActivities = len(activities)
		data.NumOfSubjects = len(subjects)
		data.NumOfClasses = len(classes)

		if err := renderer.Render(w, "base", "school_show", data); err != nil {
			panic(err)
		}
	}
	return http.HandlerFunc(fn)
}

func saveSchool(r *http.Request, school *orm.School) {
	if err := r.ParseForm(); err != nil {
		panic(err)
	}

	decoder := schema.NewDecoder()
	if err := decoder.Decode(school, r.PostForm); err != nil {
		panic(err)
	}

	if err := orm.DB().Save(school).Error; err != nil {
		panic(err)
	}

}

func schoolUpdateHandler() http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		if r.Method == "GET" {
			var data struct {
				Update bool
				School orm.School
			}

			if !orm.DB().First(&data.School, mux.Vars(r)["id"]).RecordNotFound() {
				if err := orm.DB().First(&data.School, mux.Vars(r)["id"]).Error; err != nil {
					panic(err)
				}
			}

			data.Update = true

			if err := renderer.Render(w, "base", "school_update", data); err != nil {
				panic(err)
			}
		} else if r.Method == "POST" {
			var school orm.School

			if !orm.DB().First(&school, mux.Vars(r)["id"]).RecordNotFound() {
				if err := orm.DB().First(&school, mux.Vars(r)["id"]).Error; err != nil {
					panic(err)
				}
			}

			saveSchool(r, &school)

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

	}
	return http.HandlerFunc(fn)
}
