package api

import (
	"fmt"
	"log"
	"net/http"

	"gogs.carducci-dante.gov.it/karmen/core/orm"
	"gogs.carducci-dante.gov.it/karmen/core/renderer"
)

func dashboardHandler() 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 {
				NumOfTeachers   int
				NumOfSubjects   int
				NumOfClasses    int
				NumOfActivities int
				Issues          []orm.Issue
			}
		)

		if err := orm.DB().Preload("Teacher").Find(&data.Issues).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 r.URL.Query().Get("reload_issues") == "true" {

			log.Println("Reloading issues...")

			for _, teacher := range teachers {
				teacher.CalcHours(orm.DB())
				orm.DB().Where("teacher_id = ?", teacher.ID).Delete(&orm.Issue{})
				teacher.CheckForIssues(orm.DB())
			}
			http.Redirect(w, r, fmt.Sprintf("/"), http.StatusSeeOther)
		}
		if err := renderer.Render(w, "base", "dashboard", data); err != nil {
			panic(err)
		}
	}
	return http.HandlerFunc(fn)
}
