▍ humdrum codex / sportsball v0.1.0
license AGPL-3.0
2.2 KB raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package ui

import (
	"github.com/humdrum-tiv/sportsball/internal/config"
	"github.com/humdrum-tiv/sportsball/internal/model"
)

// favKey is the stable identity of a favorited team: league + ESPN team id,
// falling back to the abbreviation when no id is present.
func favKey(league model.LeagueID, t model.Team) string {
	id := t.ID
	if id == "" {
		id = t.Abbr
	}
	return string(league) + ":" + id
}

// loadFavorites builds the in-memory favorites set from persisted config.
func loadFavorites(cfg config.Config) map[string]bool {
	favs := make(map[string]bool, len(cfg.Favorites))
	for _, f := range cfg.Favorites {
		id := f.ID
		if id == "" {
			id = f.Abbr
		}
		favs[f.League+":"+id] = true
	}
	return favs
}

// isFav reports whether a team is favorited.
func (a App) isFav(league model.LeagueID, t model.Team) bool {
	return a.favs[favKey(league, t)]
}

// hasFav reports whether either side of a game is a favorite.
func (a App) hasFav(g model.Game) bool {
	return a.isFav(g.League, g.Home) || a.isFav(g.League, g.Away)
}

// toggleFav flips a team's favorite state and persists the change. Persistence
// is best-effort: a write failure leaves the in-memory toggle intact.
func (a *App) toggleFav(league model.LeagueID, t model.Team) {
	key := favKey(league, t)
	if a.favs[key] {
		delete(a.favs, key)
	} else {
		a.favs[key] = true
	}
	a.cfg.Favorites = a.favoritesList()
	_ = config.Save(a.cfg)
}

// favoritesList rebuilds the persisted favorites slice from current data,
// preserving display fields by scanning loaded games for each key.
func (a App) favoritesList() []config.FavTeam {
	out := make([]config.FavTeam, 0, len(a.favs))
	seen := map[string]bool{}
	for _, games := range a.games {
		for _, g := range games {
			for _, t := range []model.Team{g.Home, g.Away} {
				key := favKey(g.League, t)
				if a.favs[key] && !seen[key] {
					seen[key] = true
					out = append(out, config.FavTeam{
						League: string(g.League), ID: t.ID, Abbr: t.Abbr, Name: t.Name,
					})
				}
			}
		}
	}
	// Keep any favorites we couldn't resolve to a loaded game (id-only).
	for _, f := range a.cfg.Favorites {
		id := f.ID
		if id == "" {
			id = f.Abbr
		}
		key := f.League + ":" + id
		if a.favs[key] && !seen[key] {
			seen[key] = true
			out = append(out, f)
		}
	}
	return out
}