moth/cmd/mothd/award.go

79 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
2018-09-17 17:00:08 -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 {
return len(awards)
}
func (awards AwardList) Less(i, j int) bool {
return awards[i].When.Before(awards[j].When)
}
func (awards AwardList) Swap(i, j int) {
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
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 {
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,
a.TeamId,
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 {
case a.TeamId != o.TeamId:
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
}