package api

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

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

func teacherSubjectsAdd() 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_subjects struct {
			Ids []string `json:"ids"`
		}

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

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

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

		for _, subjectId := range selected_subjects.Ids {
			var subject orm.Subject
			if err := orm.DB().First(&subject, subjectId).Error; err != nil {
				panic(err)
			}

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

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

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

	}
	return http.HandlerFunc(fn)
}

func teachersSubjectsDelete() http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		var (
			teacher orm.Teacher
			subject orm.Subject
		)

		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)["subject_id"]).Find(&subject).Error; err != nil {
			panic(err)
		}

		if err := orm.DB().Model(&teacher).Association("Subjects").Delete(&subject).Error; err != nil {
			panic(err)
		}
	}
	return http.HandlerFunc(fn)
}
