aboutsummaryrefslogtreecommitdiff
path: root/src/lib/stores/games.svelte.js
blob: ae76ce364beaaae8dabe8047b1c19f3cd07357fb (plain) (blame)
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
86
87
88
89
90
91
import { createGame, createTeam } from "../logic/players.js";
import {
  proposeGames,
  createDefaultGames,
  collectConfirmedPlayerNames,
} from "../logic/matchmaking.js";
import {
  getCourts,
} from "./courts.svelte.js";
import {
  getRegulars,
  incrementRegularGames,
  resetRegulars,
} from "./regulars.svelte.js";
import { getGuests, incrementGuestGames } from "./guests.svelte.js";
import { getSkillFactor } from "./skillFactor.svelte.js";
import { start as startTimer, stopTimer } from "./timer.svelte.js";

const GAMES_STORAGE_KEY = "Game";
const ROUND_STORAGE_KEY = "round";
const GAME_COUNT = 12;

function loadInitialGames() {
  const stored = JSON.parse(localStorage.getItem(GAMES_STORAGE_KEY));
  if (stored && stored.length > 0) {
    return stored.map((g) =>
      createGame(
        Number(g.id),
        Boolean(g.status),
        createTeam(g.teamOne.playerOne, g.teamOne.playerTwo),
        createTeam(g.teamTwo.playerOne, g.teamTwo.playerTwo)
      )
    );
  }
  return createDefaultGames(GAME_COUNT);
}

let games = $state(loadInitialGames());
let round = $state(Number(localStorage.getItem(ROUND_STORAGE_KEY)) || 0);

function persistGames() {
  localStorage.setItem(GAMES_STORAGE_KEY, JSON.stringify(games));
}

export function getGames() {
  return games;
}

export function getRound() {
  return round;
}

export function getGameDescription() {
  const confirmed = games[0]?.status;
  return confirmed ? `Round ${round}` : "Proposal";
}

export function propose() {
  games = proposeGames({
    courts: getCourts(),
    regulars: getRegulars(),
    guests: getGuests(),
    skillFactor: getSkillFactor(),
  });
}

export function confirm() {
  const alreadyConfirmed = games[0]?.status;
  if (alreadyConfirmed) return;

  round += 1;
  localStorage.setItem(ROUND_STORAGE_KEY, round);
  for (const game of games) game.status = true;

  const selectedNames = collectConfirmedPlayerNames(games);
  incrementRegularGames(selectedNames);
  incrementGuestGames(selectedNames);

  persistGames();
  startTimer(true);
}

export function resetSession() {
  localStorage.removeItem(ROUND_STORAGE_KEY);
  localStorage.removeItem(GAMES_STORAGE_KEY);
  localStorage.removeItem("Court");
  localStorage.removeItem("Guest");
  resetRegulars();
  stopTimer();
  window.location.reload();
}