probo/sessionmanager/sessionmanager.go
2023-12-12 09:22:07 +01:00

83 lines
1.6 KiB
Go

package sessionmanager
import (
"bytes"
"encoding/json"
"io"
"net/http"
"git.andreafazzi.eu/andrea/probo/models"
"git.andreafazzi.eu/andrea/probo/store"
)
type SessionManager struct {
Name string
ParticipantStore *store.ParticipantStore
QuizStore *store.QuizStore
ParticipantFilter map[string]string
QuizFilter map[string]string
ServerURL string
Token int
examStore *store.ExamStore
}
func NewSessionManager(url string, name string, pStore *store.ParticipantStore, qStore *store.QuizStore, pFilter map[string]string, qFilter map[string]string) (*SessionManager, error) {
sm := new(SessionManager)
sm.Name = name
sm.ServerURL = url
sm.examStore = store.NewStore[*models.Exam]()
for _, p := range pStore.ReadAll() {
_, err := sm.examStore.Create(&models.Exam{
Participant: p,
Quizzes: qStore.ReadAll(),
})
if err != nil {
return nil, err
}
}
return sm, nil
}
func (sm *SessionManager) GetExams() []*models.Exam {
return sm.examStore.ReadAll()
}
func (sm *SessionManager) Push() (string, error) {
session := &models.Session{
Name: sm.Name,
Exams: make(map[string]*models.Exam),
}
for _, e := range sm.GetExams() {
session.Exams[e.Participant.Token] = e
}
payload, err := session.Marshal()
if err != nil {
return "", err
}
response, err := http.Post(sm.ServerURL, "application/json", bytes.NewReader(payload))
if err != nil {
return "", err
}
responseBody, err := io.ReadAll(response.Body)
if err != nil {
return "", err
}
result := map[string]string{}
err = json.Unmarshal(responseBody, &result)
if err != nil {
return "", err
}
return result["id"], nil
}