Skip to content

Commit

Permalink
Leaderboards can save and load locally
Browse files Browse the repository at this point in the history
  • Loading branch information
DaltonSW committed Oct 5, 2024
1 parent fa783d2 commit c01e256
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 4 deletions.
4 changes: 2 additions & 2 deletions cmd/aocli/aocli.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
22 changes: 20 additions & 2 deletions internal/resources/Leaderboard.go
Original file line number Diff line number Diff line change
@@ -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"
Expand Down Expand Up @@ -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,
Expand All @@ -58,6 +74,8 @@ func NewLeaderboard(year, day int) *Leaderboard {

lb.LoadPlacings()

lb.SaveResource()

return lb
}

Expand Down
5 changes: 5 additions & 0 deletions internal/utils/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"os"
"os/exec"
"runtime"
"strconv"
"strings"
"time"

Expand Down Expand Up @@ -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)
}

0 comments on commit c01e256

Please sign in to comment.