oef/orm/response.go
2019-12-19 12:12:56 +01:00

238 lines
5.5 KiB
Go

package orm
import (
"fmt"
"log"
"net/http"
"strconv"
"strings"
"time"
"git.andreafazzi.eu/andrea/oef/renderer"
"github.com/jinzhu/gorm"
)
type SingleResponse struct {
AnswerID uint
}
type Response struct {
gorm.Model
*UserModifierCreate
*UserModifierUpdate
Name string
Participant *Participant
ParticipantID uint
Contest *Contest
ContestID uint
QuestionsOrder string
AnswersIDs string
StartTime time.Time
EndTime time.Time
TimeLeft time.Duration
Score int `gorm:"-"`
Questions []*Question
SingleResponses []*SingleResponse `gorm:"-"`
}
func (sr *SingleResponse) UnmarshalText(text []byte) error {
id, err := strconv.Atoi(string(text))
sr.AnswerID = uint(id)
if err != nil {
return err
}
return nil
}
func (model *Response) GetID() uint { return model.ID }
func (model *Response) String() string {
return model.Name
}
func (model *Response) generateAnswersIDs() string {
ids := make([]string, 0)
for _, sr := range model.SingleResponses {
ids = append(ids, strconv.Itoa(int(sr.AnswerID)))
}
return strings.Join(ids, " ")
}
func (model *Response) BeforeSave(tx *gorm.DB) error {
model.AnswersIDs = model.generateAnswersIDs()
return nil
}
func (model *Response) Create(args map[string]string, w http.ResponseWriter, r *http.Request) (interface{}, error) {
if r.Method == "GET" {
response := new(Response)
contestID := r.URL.Query().Get("contest_id")
if err := DB().Preload("Answers").Where("contest_id = ?", contestID).Find(&response.Questions).Error; err != nil {
return nil, err
}
return response, nil
} else {
response := new(Response)
err := renderer.Decode(response, r)
if err != nil {
return nil, err
}
response.UserModifierCreate = NewUserModifierCreate(r)
response, err = CreateResponse(response)
if err != nil {
return nil, err
}
return response, nil
}
}
func (model *Response) Read(args map[string]string, w http.ResponseWriter, r *http.Request) (interface{}, error) {
var response Response
id := args["id"]
if err := DB().Preload("Contest").Preload("Participant").First(&response, id).Error; err != nil {
return nil, err
}
if response.AnswersIDs != "" {
srIDs := strings.Split(response.AnswersIDs, " ")
for _, srID := range srIDs {
id, err := strconv.Atoi(srID)
if err != nil {
return nil, err
}
response.SingleResponses = append(response.SingleResponses, &SingleResponse{uint(id)})
}
for _, sr := range response.SingleResponses {
var answer Answer
if err := DB().First(&answer, sr.AnswerID).Error; err != nil {
return nil, err
}
if answer.Correct {
response.Score++
}
}
}
qOrder := make([]uint, 0)
qIDs := strings.Split(response.QuestionsOrder, " ")
for _, id := range qIDs {
id, err := strconv.Atoi(id)
if err != nil {
return nil, err
}
qOrder = append(qOrder, uint(id))
}
// Fetch questions in the given order
field := fmt.Sprintf("FIELD(id,%s)", strings.Replace(response.QuestionsOrder, " ", ",", -1))
if err := DB().Order(field).Where("contest_id = ?", response.Contest.ID).Preload("Answers", func(db *gorm.DB) *gorm.DB {
return db.Order("RAND()")
}).Find(&response.Questions).Error; err != nil {
return nil, err
}
return &response, nil
}
func (model *Response) ReadAll(args map[string]string, w http.ResponseWriter, r *http.Request) (interface{}, error) {
var responses []*Response
if err := DB().Preload("Contest").Preload("Participant").Order("created_at").Find(&responses).Error; err != nil {
return nil, err
}
return responses, nil
}
func (model *Response) Update(args map[string]string, w http.ResponseWriter, r *http.Request) (interface{}, error) {
if r.Method == "GET" {
result, err := model.Read(args, w, r)
if err != nil {
return nil, err
}
response := result.(*Response)
// Write StartTime for the first time if user is a participant
if isParticipant(r) && !response.Contest.StartTime.IsZero() && !response.Contest.EndTime.IsZero() {
if response.StartTime.IsZero() {
if err := DB().Model(&response).Update("start_time", time.Now()).Error; err != nil {
return nil, err
}
if err := DB().Model(&response).Update("end_time", time.Now().Add(time.Duration(response.Contest.Duration)*time.Minute)).Error; err != nil {
return nil, err
}
log.Println("StartTime/EndTime", response.StartTime, response.EndTime)
}
response.TimeLeft = response.EndTime.Sub(time.Now())
log.Println("TimeLeft:", response.TimeLeft)
}
return response, nil
} else {
response, err := model.Read(args, w, r)
if err != nil {
return nil, err
}
err = renderer.Decode(response, r)
if err != nil {
return nil, err
}
response.(*Response).UserModifierUpdate = NewUserModifierUpdate(r)
_, err = SaveResponse(response)
if err != nil {
return nil, err
}
response, err = model.Read(args, w, r)
if err != nil {
return nil, err
}
return response.(*Response), nil
}
}
func (model *Response) Delete(args map[string]string, w http.ResponseWriter, r *http.Request) (interface{}, error) {
response, err := model.Read(args, w, r)
if err != nil {
return nil, err
}
if err := DB().Unscoped().Delete(response.(*Response)).Error; err != nil {
return nil, err
}
return response.(*Response), nil
}
func CreateResponse(response *Response) (*Response, error) {
if err := DB().Create(response).Error; err != nil {
return nil, err
}
return response, nil
}
func SaveResponse(response interface{}) (interface{}, error) {
if err := DB(). /*.Omit("Something")*/ Save(response).Error; err != nil {
return nil, err
}
return response, nil
}