package api

import (
	"encoding/json"
	"net/http"

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

func teacherClassesAdd() http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		var teacher orm.Teacher
		if err := orm.DB().First(&teacher, mux.Vars(r)["id"]).Error; err != nil {
			panic(err)
		}

		var selected_classes struct {
			Ids []string `json:"ids"`
		}

		if err := json.NewDecoder(r.Body).Decode(&selected_classes); err != nil {
			panic(err)
		}

		var data struct {
			Classes []orm.Class `json:"elements"`
			Name1   string      `json:"name1"`
			Name2   string      `json:"name2"`
			Id1     uint        `json:"id1"`
			Id2     []uint      `json:"id2"`
		}

		data.Name1 = "teachers"
		data.Name2 = "classes"
		data.Id1 = teacher.ID

		for _, classId := range selected_classes.Ids {
			var class orm.Class
			if err := orm.DB().First(&class, classId).Error; err != nil {
				panic(err)
			}

			// Check if the association exists
			var output []orm.Class

			if err := orm.DB().Model(&teacher).Where("class_id = ? and teacher_id = ?", classId, teacher.ID).Related(&output, "Classes").Error; err != nil {
				panic(err)
			}
			if len(output) == 0 {
				if err := orm.DB().Model(&teacher).Association("Classes").Append(&class).Error; err != nil {
					panic(err)
				}
				data.Classes = append(data.Classes, class)
				data.Id2 = append(data.Id2, class.ID)
			}
		}

		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(data)

	}
	return http.HandlerFunc(fn)
}

func teachersClassesDelete() http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		var (
			teacher orm.Teacher
			class   orm.Class
		)

		if err := orm.DB().Where("id = ?", mux.Vars(r)["id"]).Find(&teacher).Error; err != nil {
			panic(err)
		}

		if err := orm.DB().Where("id = ?", mux.Vars(r)["class_id"]).Find(&class).Error; err != nil {
			panic(err)
		}

		if err := orm.DB().Model(&teacher).Association("Classes").Delete(&class).Error; err != nil {
			panic(err)
		}

		if teacher.ID == class.CoordinatorID {
			class.CoordinatorID = 0
			if err := orm.DB().Save(&class).Error; err != nil {
				panic(err)
			}

		}

		if teacher.ID == class.MinuterID {
			class.MinuterID = 0
			if err := orm.DB().Save(&class).Error; err != nil {
				panic(err)
			}
		}

	}
	return http.HandlerFunc(fn)
}
