import { merge } from 'lodash-es' import { reactive, watch } from 'vue' // import { plausible } from '@/analytics' import { LSK_STATS } from '@/globals' import * as storage from '@/storage' import { GameStats } from '@/types' // import { getCurrentSessionKey } from '@/utils' // import { countTotalGuesses, isWinner } from './game-state' export const gameStats = reactive(loadStats()) // Triggered when the list of played games has changed watch( () => gameStats.games, games => { const keys = Object.keys(games).sort() // Recompute games count gameStats.bestStreak = 0 gameStats.currentStreak = 0 gameStats.nbGames = keys.length for (const key of keys) { if (gameStats.games[key].won) { if (++gameStats.currentStreak > gameStats.bestStreak) { gameStats.bestStreak = gameStats.currentStreak } } else { gameStats.currentStreak = 0 } } // Automatically save stats in storage when updated storage.setItem(LSK_STATS, JSON.stringify(gameStats)) }, { deep: true, immediate: true }, ) function loadStats(): GameStats { const stats: GameStats = { bestStreak: 0, currentStreak: 0, nbGames: 0, games: {}, } const loaded = (() => { try { return JSON.parse(storage.getItem(LSK_STATS)!) } catch (e) { return {} } })() merge(stats, loaded) return stats } function setScore(seed: string, won: boolean, score: number): void { // Don't overwrite an existing score if (!gameStats.games[seed]) { gameStats.games[seed] = { score, won } // plausible.trackEvent(won ? 'win_game' : 'lose_game') // plausible.trackEvent('end_game') } } export function hasPlayed(seed:string): boolean { return !!gameStats.games[seed] } // export function saveScore(): void { // setScore(getCurrentSessionKey(), isWinner.value, countTotalGuesses.value) // }