package controllers
import (
"fmt"
"html/template"
"net/http"
"sprechstundentool/models"
"strconv"
)
// BaseHandler will hold everything that controller needs
type BaseHandler struct {
roomRepo models.RoomRepository
officeHourRepo models.OfficeHourRepository
courseRepo models.CourseRepository
tutorRepo models.TutorRepository
}
// NewBaseHandler returns a new BaseHandler
func NewBaseHandler(roomRepo models.RoomRepository, officeHourRepo models.OfficeHourRepository, courseRepo models.CourseRepository, tutorRepo models.TutorRepository) *BaseHandler {
return &BaseHandler{roomRepo, officeHourRepo, courseRepo, tutorRepo}
}
func (b *BaseHandler) RootHandler(w http.ResponseWriter, req *http.Request) {
b.writeTimetablePage(w, req, template.HTML(""))
}
func (b *BaseHandler) GetByRoomHandler(w http.ResponseWriter, req *http.Request) {
roomId, _ := strconv.Atoi(req.FormValue("raum"))
room, err := b.roomRepo.FindById(roomId)
if err != nil {
fmt.Println(err)
b.RootHandler(w, req)
return
}
officeHours, _ := b.officeHourRepo.FindByRoom(room)
b.writeTimetablePage(w, req, printTimetable(GetTimetable(officeHours)))
}
func (b *BaseHandler) GetByCourseHandler(w http.ResponseWriter, req *http.Request) {
courseid, err := strconv.Atoi(req.FormValue("veranstaltung"))
if err != nil {
b.RootHandler(w, req)
}
course, err := b.courseRepo.FindById(courseid)
if err != nil {
b.RootHandler(w, req)
return
}
officeHours, _ := b.officeHourRepo.FindByCourse(course)
b.writeTimetablePage(w, req, printTimetable(GetTimetable(officeHours)))
}
func (b *BaseHandler) writeTimetablePage(w http.ResponseWriter, req *http.Request, timetable template.HTML) {
courses, _ := b.courseRepo.GetAll()
rooms, _ := b.roomRepo.GetAll()
selectedRoom, _ := strconv.Atoi(req.FormValue("raum"))
selectedCourse, _ := strconv.Atoi(req.FormValue("veranstaltung"))
data := struct {
Courses []models.Course
Rooms []models.Room
Timetable template.HTML
SelectedRoom int
SelectedCourse int
}{courses, rooms, timetable, selectedRoom, selectedCourse}
tmpl, err := template.ParseFiles("templates/index.html")
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(fmt.Sprintf("Template konnte nicht geparst werden : %s", string(err.Error()))))
return
}
err = tmpl.Execute(w, data)
if err != nil {
w.Write([]byte(fmt.Sprintf("Template konnte nicht geparst werden : %s", string(err.Error()))))
return
}
}