moth/cmd/mothd/award.go

78 lines
1.3 KiB
Go
Raw Normal View History

2018-09-14 18:24:48 -06:00
package main
import (
2020-02-29 22:37:22 -07:00
"encoding/json"
2018-09-14 18:24:48 -06:00
"fmt"
"strings"
)
type Award struct {
// Unix epoch time of this event
When int64
2020-08-14 20:26:04 -06:00
TeamID string
2018-09-14 18:24:48 -06:00
Category string
2018-09-17 17:00:08 -06:00
Points int
2018-09-14 18:24:48 -06:00
}
type AwardList []*Award
// Implement sort.Interface on AwardList
func (awards AwardList) Len() int {
2020-08-14 20:26:04 -06:00
return len(awards)
}
func (awards AwardList) Less(i, j int) bool {
2020-08-14 20:26:04 -06:00
return awards[i].When < awards[j].When
}
func (awards AwardList) Swap(i, j int) {
2020-08-14 20:26:04 -06:00
tmp := awards[i]
awards[i] = awards[j]
awards[j] = tmp
}
2018-09-17 18:02:44 -06:00
func ParseAward(s string) (*Award, error) {
ret := Award{}
2018-09-18 21:29:05 -06:00
s = strings.TrimSpace(s)
2018-09-17 18:02:44 -06:00
2020-08-14 20:26:04 -06:00
n, err := fmt.Sscanf(s, "%d %s %s %d", &ret.When, &ret.TeamID, &ret.Category, &ret.Points)
2018-09-17 18:02:44 -06:00
if err != nil {
return nil, err
} else if n != 4 {
return nil, fmt.Errorf("Malformed award string: only parsed %d fields", n)
}
return &ret, nil
}
2018-09-14 18:24:48 -06:00
func (a *Award) String() string {
2020-08-14 20:26:04 -06:00
return fmt.Sprintf("%d %s %s %d", a.When, a.TeamID, a.Category, a.Points)
2018-09-17 17:00:08 -06:00
}
2020-02-29 18:36:59 -07:00
func (a *Award) MarshalJSON() ([]byte, error) {
2020-02-29 22:37:22 -07:00
if a == nil {
return []byte("null"), nil
}
ao := []interface{}{
a.When,
2020-08-14 20:26:04 -06:00
a.TeamID,
2020-02-29 22:37:22 -07:00
a.Category,
a.Points,
}
return json.Marshal(ao)
2020-02-29 18:36:59 -07:00
}
2018-09-17 18:02:44 -06:00
func (a *Award) Same(o *Award) bool {
switch {
2020-08-14 20:26:04 -06:00
case a.TeamID != o.TeamID:
2018-09-17 18:02:44 -06:00
return false
case a.Category != o.Category:
2018-09-17 21:32:24 -06:00
return false
2018-09-17 18:02:44 -06:00
case a.Points != o.Points:
return false
2018-09-14 18:24:48 -06:00
}
2018-09-17 18:02:44 -06:00
return true
2018-09-17 21:32:24 -06:00
}