package main
import (
"fmt"
"html/template"
"log"
"net/http"
"streifling.com/jason/sicherheitsunterweisung/packages/db"
"streifling.com/jason/sicherheitsunterweisung/packages/server"
"streifling.com/jason/sicherheitsunterweisung/packages/types"
)
func handleParticipants(mux *http.ServeMux, db *db.DB, cp <-chan *types.Participant, s *types.Session) {
for participant := range cp {
mux.HandleFunc("/submit-participant/"+fmt.Sprint(s.ID)+"/"+fmt.Sprint(participant.Login)+"/", server.HandleParticipant(s, participant, &s.Questions, db))
for i := range s.Questions {
mux.HandleFunc("/submit-answer/"+fmt.Sprint(s.ID)+"/"+fmt.Sprint(participant.Login)+"/"+fmt.Sprint(i+1)+"/", server.HandleAnswer(s, db, participant, &s.Questions, int64(i+1)))
}
mux.HandleFunc("/retry/"+fmt.Sprint(s.ID)+"/"+fmt.Sprint(participant.Login)+"/", server.HandleRetry(s, participant, &s.Questions))
}
}
func handleSessions(mux *http.ServeMux, db *db.DB, cs <-chan *types.Session, ss *[]*types.Session) {
for session := range cs {
(*ss) = append(*ss, session)
participantChan := make(chan *types.Participant)
questionIDs := make([]string, 4)
for i := 0; i < len(questionIDs); i++ {
questionIDs[i] = fmt.Sprint(i + 1)
}
var err error
session.Questions, err = db.GetQuestions(questionIDs)
if err != nil {
log.Fatalln(err)
}
mux.HandleFunc("/new-briefing/", server.HandleNewBriefing(session))
mux.HandleFunc("/new-participant/"+fmt.Sprint(session.ID)+"/", server.HandleNewParticipant(session, participantChan))
mux.HandleFunc("/submit-form/"+fmt.Sprint(session.ID)+"/", server.HandleBriefingForm(session, db))
go handleParticipants(mux, db, participantChan, session)
}
}
func main() {
db, err := db.Open("sicherheitsunterweisung")
if err != nil {
log.Fatalln(err)
}
mux := http.NewServeMux()
sessions := make([]*types.Session, 0)
sessionChan := make(chan *types.Session)
mux.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static/"))))
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
template.Must(template.ParseFiles("templates/index.html", "templates/login.html")).Execute(w, nil)
})
mux.HandleFunc("/internal-login/", server.HandleInternalLogin(&sessions, sessionChan, db))
mux.HandleFunc("/external-login/", server.HandleExternalLogin(&sessions))
mux.HandleFunc("/search/", server.HandleSearch(db))
go handleSessions(mux, db, sessionChan, &sessions)
log.Fatalln(http.ListenAndServe(":8080", mux))
}