import 'dart:convert'; import 'package:shared_preferences/shared_preferences.dart'; import '../core/app_colors.dart'; class StorageService { static final StorageService instance = StorageService._internal(); StorageService._internal(); late SharedPreferences _prefs; // Si avvia quando apriamo l'app Future init() async { _prefs = await SharedPreferences.getInstance(); } // --- IMPOSTAZIONI --- int get savedThemeIndex => _prefs.getInt('theme') ?? AppThemeType.cyberpunk.index; Future saveTheme(AppThemeType theme) async => await _prefs.setInt('theme', theme.index); int get savedRadius => _prefs.getInt('radius') ?? 2; Future saveRadius(int radius) async => await _prefs.setInt('radius', radius); bool get isMuted => _prefs.getBool('isMuted') ?? false; Future saveMuted(bool muted) async => await _prefs.setBool('isMuted', muted); // --- STATISTICHE VS CPU --- int get wins => _prefs.getInt('wins') ?? 0; Future addWin() async => await _prefs.setInt('wins', wins + 1); int get losses => _prefs.getInt('losses') ?? 0; Future addLoss() async => await _prefs.setInt('losses', losses + 1); int get cpuLevel => _prefs.getInt('cpuLevel') ?? 1; Future saveCpuLevel(int level) async => await _prefs.setInt('cpuLevel', level); // --- MULTIPLAYER --- String get playerName => _prefs.getString('playerName') ?? ''; Future savePlayerName(String name) async => await _prefs.setString('playerName', name); // --- STORICO PARTITE --- List> get matchHistory { List history = _prefs.getStringList('matchHistory') ?? []; return history.map((e) => jsonDecode(e) as Map).toList(); } // Salviamo sia il nostro nome che quello dell'avversario Future saveMatchToHistory({required String myName, required String opponent, required int myScore, required int oppScore, required bool isOnline}) async { List history = _prefs.getStringList('matchHistory') ?? []; Map match = { 'date': DateTime.now().toIso8601String(), 'myName': myName, 'opponent': opponent, 'myScore': myScore, 'oppScore': oppScore, 'isOnline': isOnline, }; // Aggiungiamo in cima (il più recente per primo) history.insert(0, jsonEncode(match)); // Teniamo solo le ultime 50 partite per non intasare la memoria if (history.length > 50) { history = history.sublist(0, 50); } await _prefs.setStringList('matchHistory', history); } }