package main

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

	"streifling.com/jason/sicherheitsunterweisung/packages/data"
	"streifling.com/jason/sicherheitsunterweisung/packages/server"
	"streifling.com/jason/sicherheitsunterweisung/packages/types"
)

func waitForParticipants(sb []*types.Briefing, sp []*types.Participant, cp <-chan *types.Participant, m *http.ServeMux) {
	for p := range cp {
		p.Questions = data.InitQuestions()
		sp = append(sp, p)

		var i int
		for i = range p.Questions {
			m.HandleFunc("/display-question-"+fmt.Sprintf("%d", p.ID)+"-"+fmt.Sprintf("%d", i)+"/", server.DisplayQuestion(i, p))
		}
		m.HandleFunc("/display-question-"+fmt.Sprintf("%d", p.ID)+"-"+fmt.Sprintf("%d", i+1)+"/", server.DisplayTestResults(sb, p))
	}
}

func main() {
	logins := make([]string, 0)
	participants := make([]*types.Participant, 0)
	briefings := make([]*types.Briefing, 0)
	mux := http.NewServeMux()

	db, err := data.OpenDB("sicherheitsunterweisung")
	if err != nil {
		log.Fatalln(err)
	}

	var i, j int64
	if err := db.GetLastID(&i); err != nil {
		log.Fatalln(err)
	}
	j = i

	participantChan := make(chan *types.Participant)
	defer close(participantChan)
	go waitForParticipants(briefings, participants, participantChan, mux)

	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("/search/", server.DisplaySearchResults(db))
	mux.HandleFunc("/new-briefing/", server.DisplayForm(&i))
	mux.HandleFunc("/add-participant/", server.AddParticipant(&i, &logins))
	mux.HandleFunc("/submit-form/", server.SubmitForm(db, &i, &j))
	mux.HandleFunc("/internal-login/", server.DisplayTable(db))
	mux.HandleFunc("/external-login/", server.DisplayParticipantForm(&logins, participantChan))

	log.Fatalln(http.ListenAndServe(":8080", mux))
}
