ictgj-voting/model_votes.go

114 lines
2.3 KiB
Go
Raw Normal View History

package main
2017-06-30 19:35:36 +00:00
import (
2017-07-28 19:36:14 +00:00
"fmt"
2017-06-30 19:35:36 +00:00
"strconv"
2017-07-06 17:09:49 +00:00
"strings"
2017-06-30 19:35:36 +00:00
"time"
)
2017-06-30 19:35:36 +00:00
// A Choice is a ranking of a game in a vote
type GameChoice struct {
Team string // UUID of team
Rank int
}
// A Vote is a collection of game rankings
type Vote struct {
Timestamp time.Time
2017-06-30 19:35:36 +00:00
ClientId string // UUID of client
Choices []GameChoice
}
func dbGetAllVotes() []Vote {
var ret []Vote
var err error
if err = db.OpenDB(); err != nil {
return ret
}
defer db.CloseDB()
votesBkt := []string{"votes"}
2017-06-30 19:35:36 +00:00
var clients []string
if clients, err = db.GetBucketList(votesBkt); err != nil {
// Couldn't get the list of clients
return ret
}
for _, clid := range clients {
ret = append(ret, dbGetClientVotes(clid)...)
}
return ret
}
2017-06-30 19:35:36 +00:00
func dbGetClientVotes(clientId string) []Vote {
var ret []Vote
var err error
if err = db.OpenDB(); err != nil {
2017-06-30 19:35:36 +00:00
return ret
}
defer db.CloseDB()
2017-06-30 19:35:36 +00:00
var times []string
votesBkt := []string{"votes", clientId}
if times, err = db.GetBucketList(votesBkt); err != nil {
return ret
}
for _, t := range times {
var tm time.Time
if tm, err = time.Parse(time.RFC3339, t); err == nil {
var vt *Vote
if vt, err = dbGetVote(clientId, tm); err == nil {
ret = append(ret, *vt)
2017-07-28 19:36:14 +00:00
} else {
fmt.Println(err)
2017-06-30 19:35:36 +00:00
}
}
}
return ret
}
2017-06-30 19:35:36 +00:00
func dbGetVote(clientId string, timestamp time.Time) (*Vote, error) {
var err error
if err = db.OpenDB(); err != nil {
return nil, err
}
defer db.CloseDB()
vt := new(Vote)
vt.Timestamp = timestamp
vt.ClientId = clientId
votesBkt := []string{"votes", clientId, timestamp.Format(time.RFC3339)}
var choices []string
2017-07-06 17:09:49 +00:00
if choices, err = db.GetKeyList(votesBkt); err != nil {
2017-06-30 19:35:36 +00:00
// Couldn't find the vote...
return nil, err
}
for _, v := range choices {
ch := new(GameChoice)
var rank int
2017-07-06 17:09:49 +00:00
2017-06-30 19:35:36 +00:00
if rank, err = strconv.Atoi(v); err == nil {
ch.Rank = rank
ch.Team, err = db.GetValue(votesBkt, v)
vt.Choices = append(vt.Choices, *ch)
}
}
return vt, nil
}
func dbSaveVote(clientId string, timestamp time.Time, votes []string) error {
var err error
if err = db.OpenDB(); err != nil {
return nil
}
defer db.CloseDB()
2017-06-30 19:35:36 +00:00
// Make sure we don't clobber a duplicate vote
votesBkt := []string{"votes", clientId, timestamp.Format(time.RFC3339)}
for i := range votes {
2017-07-06 17:09:49 +00:00
if strings.TrimSpace(votes[i]) != "" {
db.SetValue(votesBkt, strconv.Itoa(i), votes[i])
}
2017-06-30 19:35:36 +00:00
}
return err
}