79 lines
1.8 KiB
Go
79 lines
1.8 KiB
Go
package setup
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
|
|
"forge.cadoles.com/wpetit/kouiz/internal/config"
|
|
"forge.cadoles.com/wpetit/kouiz/internal/http/handler/webui/quiz"
|
|
"forge.cadoles.com/wpetit/kouiz/internal/store"
|
|
"forge.cadoles.com/wpetit/kouiz/misc/quiz/openquizzdb"
|
|
"github.com/pkg/errors"
|
|
"gorm.io/datatypes"
|
|
)
|
|
|
|
func NewQuizHandlerFromConfig(ctx context.Context, conf *config.Config) (*quiz.Handler, error) {
|
|
store, err := getStoreFromConfig(ctx, conf)
|
|
if err != nil {
|
|
return nil, errors.WithStack(err)
|
|
}
|
|
|
|
if err := loadEmbeddedQuizz(ctx, store); err != nil {
|
|
return nil, errors.WithStack(err)
|
|
}
|
|
|
|
return quiz.NewHandler(store, conf.Quiz.PlayInterval, conf.Quiz.PlayPeriod, conf.Quiz.PlayDelay, conf.Quiz.OffDays), nil
|
|
}
|
|
|
|
func loadEmbeddedQuizz(ctx context.Context, st *store.Store) error {
|
|
quizz, err := openquizzdb.LoadAll()
|
|
if err != nil {
|
|
return errors.WithStack(err)
|
|
}
|
|
|
|
for _, q := range quizz {
|
|
c := q.Categories["fr"]
|
|
|
|
category := &store.QuizCategory{
|
|
Name: c.Name,
|
|
Theme: c.Label,
|
|
Description: c.Slogan,
|
|
}
|
|
|
|
err := st.UpsertQuizCategory(ctx, category)
|
|
if err != nil {
|
|
return errors.WithStack(err)
|
|
}
|
|
|
|
quiz := q.Quizz["fr"]
|
|
levels := [][]openquizzdb.Entry{
|
|
quiz.Beginner,
|
|
quiz.Intermediate,
|
|
quiz.Expert,
|
|
}
|
|
|
|
for i, l := range levels {
|
|
for _, e := range l {
|
|
entry := &store.QuizEntry{
|
|
CategoryID: category.ID,
|
|
Question: e.Question,
|
|
Level: uint(i),
|
|
Provider: "openquizzdb",
|
|
ProviderID: fmt.Sprintf("%d-%d-%d", category.ID, i, e.ID),
|
|
Propositions: datatypes.NewJSONSlice(e.Propositions),
|
|
Answer: e.Answer,
|
|
Anecdote: e.Anecdote,
|
|
}
|
|
|
|
err := st.UpsertQuizEntry(ctx, entry)
|
|
if err != nil {
|
|
return errors.WithStack(err)
|
|
}
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
}
|