moth/cmd/mothd/award.go

73 lines
1.2 KiB
Go
Raw Normal View History

2018-09-14 18:24:48 -06:00
package main
import (
2018-09-17 17:00:08 -06:00
"encoding/json"
2018-09-14 18:24:48 -06:00
"fmt"
"strings"
"time"
)
type Award struct {
2018-09-17 17:00:08 -06:00
When time.Time
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
}
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
var whenEpoch int64
n, err := fmt.Sscanf(s, "%d %s %s %d", &whenEpoch, &ret.TeamId, &ret.Category, &ret.Points)
if err != nil {
return nil, err
} else if n != 4 {
return nil, fmt.Errorf("Malformed award string: only parsed %d fields", n)
}
ret.When = time.Unix(whenEpoch, 0)
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.Unix(), a.TeamId, a.Category, a.Points)
}
2018-09-17 17:00:08 -06:00
func (a *Award) MarshalJSON() ([]byte, error) {
if a == nil {
return []byte("null"), nil
}
jTeamId, err := json.Marshal(a.TeamId)
if err != nil {
return nil, err
}
jCategory, err := json.Marshal(a.Category)
if err != nil {
return nil, err
}
ret := fmt.Sprintf(
"[%d,%s,%s,%d]",
a.When.Unix(),
jTeamId,
jCategory,
a.Points,
)
return []byte(ret), nil
}
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
}