From c01e256c338624936d8191b8c8d9ac6837f19f9b Mon Sep 17 00:00:00 2001 From: Dalton Williams Date: Fri, 4 Oct 2024 19:06:16 -0500 Subject: [PATCH] Leaderboards can save and load locally --- cmd/aocli/aocli.go | 4 ++-- internal/resources/Leaderboard.go | 22 ++++++++++++++++++++-- internal/utils/utils.go | 5 +++++ 3 files changed, 27 insertions(+), 4 deletions(-) diff --git a/cmd/aocli/aocli.go b/cmd/aocli/aocli.go index 4124ed0..725bbca 100644 --- a/cmd/aocli/aocli.go +++ b/cmd/aocli/aocli.go @@ -104,9 +104,9 @@ func Leaderboard(yearIn, dayIn string) { if err != nil { log.Fatal("Error parsing day from args.", "err", err) } - lb = resources.NewLeaderboard(year, day) + lb = resources.LoadOrCreateLeaderboard(year, day) } else { - lb = resources.NewLeaderboard(year, 0) + lb = resources.LoadOrCreateLeaderboard(year, 0) } if lb == nil { diff --git a/internal/resources/Leaderboard.go b/internal/resources/Leaderboard.go index d4bcbb4..69215dc 100644 --- a/internal/resources/Leaderboard.go +++ b/internal/resources/Leaderboard.go @@ -1,12 +1,15 @@ package resources import ( + "encoding/json" "fmt" "strconv" "strings" "go.dalton.dog/aocgo/internal/api" + "go.dalton.dog/aocgo/internal/cache" "go.dalton.dog/aocgo/internal/styles" + "go.dalton.dog/aocgo/internal/utils" "github.com/PuerkitoBio/goquery" "github.com/charmbracelet/lipgloss" @@ -44,9 +47,22 @@ type Leaderboard struct { BucketName string } -// NewLeaderboard will create a leaderboard object based on the parameters. +func (lb *Leaderboard) GetID() string { return utils.GetResouceBucketID(lb.Year, lb.Day) } +func (lb *Leaderboard) GetBucketName() string { return cache.PUZZLES } +func (lb *Leaderboard) MarshalData() ([]byte, error) { return json.Marshal(lb) } +func (lb *Leaderboard) SaveResource() { cache.SaveResource(lb) } + +// LoadOrCreateLeaderboard will create a leaderboard object based on the parameters. // If you want to create a leaderboard for an entire year, pass in 0 for day -func NewLeaderboard(year, day int) *Leaderboard { +func LoadOrCreateLeaderboard(year, day int) *Leaderboard { + lbData := cache.LoadResource(cache.LEADERBOARDS, utils.GetResouceBucketID(year, day)) + + if lbData != nil { + var lb *Leaderboard + json.Unmarshal(lbData, &lb) + return lb + } + lb := &Leaderboard{ Year: year, Day: day, @@ -58,6 +74,8 @@ func NewLeaderboard(year, day int) *Leaderboard { lb.LoadPlacings() + lb.SaveResource() + return lb } diff --git a/internal/utils/utils.go b/internal/utils/utils.go index d5c3455..f100802 100644 --- a/internal/utils/utils.go +++ b/internal/utils/utils.go @@ -5,6 +5,7 @@ import ( "os" "os/exec" "runtime" + "strconv" "strings" "time" @@ -78,3 +79,7 @@ func isWSL() bool { } return strings.Contains(strings.ToLower(string(data)), "microsoft") } + +func GetResouceBucketID(year, day int) string { + return strconv.Itoa(year) + strconv.Itoa(day) +}