import 'dart:convert'; import 'dart:isolate'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:shared_preferences/shared_preferences.dart'; import '../models/camera_setup.dart'; import '../models/contact.dart'; import 'club_crypto.dart'; import '../utils/target_colors.dart'; import '../utils/translations.dart'; /// Single source of truth for user settings. Loaded once in main(); widgets /// rebuild via ListenableBuilder(listenable: AppSettings.instance, ...). /// /// Writes the same SharedPreferences keys the rest of the app already reads, /// so screens can migrate to this class one at a time. class AppSettings extends ChangeNotifier { AppSettings._(); static final AppSettings instance = AppSettings._(); static const String defaultTarget = 'assets/target.png'; // Shots per target, same limit for camera and stream capture static const int minBullets = 1; static const int maxBullets = 5; static const List reminderHourOptions = [1, 2, 3, 6, 12, 24, 48]; static const List> languages = [ {'name': 'English', 'flag': '🇬🇧'}, {'name': 'Slovenian', 'flag': '🇸🇮'}, {'name': 'German', 'flag': '🇩🇪'}, ]; static const String defaultLanguage = 'Slovenian'; static const Map bulletColors = { 'Blue': Colors.blue, 'Green': Colors.green, 'Yellow': Colors.yellow, 'Purple': Colors.purple, 'Cyan': Colors.cyan, 'Teal': Colors.teal, 'Indigo': Colors.indigo, 'Pink': Colors.pink, 'Lime': Colors.lime, 'Mint': Colors.greenAccent, 'Orange': Colors.orange, 'Violet': Colors.deepPurpleAccent, 'Amber': Colors.amber, 'Brown': Colors.brown, 'Grey': Colors.grey, }; // 13 was dropped earlier; 21 and 31–34 were Christmas / Easter themes static const Set removedTargets = {13, 21, 31, 32, 33, 34}; static final List targets = [ defaultTarget, for (int i = 1; i <= 35; i++) if (!removedTargets.contains(i)) 'assets/targets/Target$i.jpg', ]; late SharedPreferences _prefs; String _language = defaultLanguage; String _bulletColorName = 'Blue'; String _selectedTarget = defaultTarget; int _reminderHours = 1; bool _notifyDezuranje = true; bool _notifySestanek = true; bool _notifyTekma = true; CameraSetup _cameras = const CameraSetup(); List? _clubContacts; // null until the club code is entered String get language => _language; /// intl locale for dates (month and day names) in [language]. static String dateLocaleFor(String language) => switch (language) { 'Slovenian' => 'sl_SI', 'German' => 'de_DE', _ => 'en_US', }; String get dateLocale => dateLocaleFor(_language); String get bulletColorName => _bulletColorName; Color get bulletColor => bulletColors[_bulletColorName] ?? Colors.blue; String get selectedTarget => _selectedTarget; Color get backgroundColor => TargetColors.getBackgroundColor(_selectedTarget); bool get isLightBackground => backgroundColor.computeLuminance() > 0.4; int get reminderHours => _reminderHours; bool get notifyDezuranje => _notifyDezuranje; bool get notifySestanek => _notifySestanek; bool get notifyTekma => _notifyTekma; CameraSetup get cameras => _cameras; /// Calendar, reminders and contacts are for club members only. bool get clubUnlocked => _clubContacts != null; List get clubContacts => _clubContacts ?? const []; String t(String key) => AppTranslations.translate(key, _language); String targetName(String path) { if (path == defaultTarget) return t('Default Target'); return t(path.replaceAll('assets/targets/', '').replaceAll('.jpg', '')); } Future load() async { _prefs = await SharedPreferences.getInstance(); // New installs start in Slovenian. Whoever had "automatic" keeps the language // it last resolved to (saved under the same key). final saved = _prefs.getString('language'); _language = languages.any((l) => l['name'] == saved) ? saved! : defaultLanguage; await _prefs.setString('language', _language); // other screens read this key await _prefs.remove('languageFollowsSystem'); final color = _prefs.getString('bulletColor') ?? 'Blue'; _bulletColorName = bulletColors.containsKey(color) ? color : 'Blue'; _selectedTarget = _prefs.getString('selectedTarget') ?? defaultTarget; if (!targets.contains(_selectedTarget)) { // Target no longer shipped: fall back so screens reading prefs don't load a missing image _selectedTarget = defaultTarget; await _prefs.setString('selectedTarget', defaultTarget); } _reminderHours = _prefs.getInt('notificationHours_single') ?? 1; _notifyDezuranje = _prefs.getBool('notifyDezuranje') ?? true; _notifySestanek = _prefs.getBool('notifySestanek') ?? true; _notifyTekma = _prefs.getBool('notifyTekma') ?? true; final clubData = _prefs.getString('clubData'); if (clubData != null) { _clubContacts = _parseContacts(clubData); _refreshClubData(); // picks up contact changes shipped in an app update } final setup = _prefs.getString('cameraSetup'); if (setup != null) { _cameras = CameraSetup.fromJson(jsonDecode(setup) as Map); } else { // Before locations existed: the six single IPs become location "Kovinar" final old = { for (int p = 1; p <= CameraSetup.maxPositions; p++) if ((_prefs.getString('cameraIP_$p') ?? '').isNotEmpty) p: {'Kovinar': _prefs.getString('cameraIP_$p')!}, }; if (old.isNotEmpty) { _cameras = CameraSetup(locations: const ['Kovinar'], ips: old, activeLocation: 'Kovinar'); await _saveCameras(); } } } Future setLanguage(String value) async { _language = value; notifyListeners(); await _prefs.setString('language', value); } Future setBulletColor(String name) async { _bulletColorName = name; notifyListeners(); await _prefs.setString('bulletColor', name); } Future setTarget(String path) async { _selectedTarget = path; notifyListeners(); await _prefs.setString('selectedTarget', path); } Future setReminderHours(int hours) async { _reminderHours = hours; notifyListeners(); await _prefs.setInt('notificationHours_single', hours); await _prefs.setStringList('notificationHours', [hours.toString()]); } Future setNotifyDezuranje(bool v) => _setNotify('notifyDezuranje', v, () => _notifyDezuranje = v); Future setNotifySestanek(bool v) => _setNotify('notifySestanek', v, () => _notifySestanek = v); Future setNotifyTekma(bool v) => _setNotify('notifyTekma', v, () => _notifyTekma = v); Future _setNotify(String key, bool value, VoidCallback apply) async { apply(); notifyListeners(); await _prefs.setBool(key, value); } Future _setCameras(CameraSetup next) async { _cameras = next; notifyListeners(); await _saveCameras(); } // Also fills the old cameraIP_1…6 keys (last chosen location) for screens // that still read them, like the spectator view. Future _saveCameras() async { await _prefs.setString('cameraSetup', jsonEncode(_cameras.toJson())); for (int p = 1; p <= CameraSetup.maxPositions; p++) { final at = p <= _cameras.positions ? _cameras.camerasAt(p) : {}; final ip = at[_cameras.activeLocation] ?? (at.isEmpty ? '' : at.values.first); await _prefs.setString('cameraIP_$p', ip); } } Future addLocation(String name) async { if (name.isEmpty || _cameras.locations.contains(name)) return false; await _setCameras(_cameras.copyWith(locations: [..._cameras.locations, name])); return true; } Future renameLocation(String from, String to) async { if (to.isEmpty || (to != from && _cameras.locations.contains(to))) return false; final ips = _cameras.ipsCopy(); for (final m in ips.values) { if (m.containsKey(from)) m[to] = m.remove(from)!; } await _setCameras(CameraSetup( locations: [for (final l in _cameras.locations) l == from ? to : l], positions: _cameras.positions, ips: ips, activeLocation: _cameras.activeLocation == from ? to : _cameras.activeLocation, clubLocation: _cameras.clubLocation == from ? to : _cameras.clubLocation, )); return true; } Future removeLocation(String name) async { final ips = _cameras.ipsCopy(); for (final m in ips.values) { m.remove(name); } await _setCameras(CameraSetup( locations: [for (final l in _cameras.locations) if (l != name) l], positions: _cameras.positions, ips: ips, activeLocation: _cameras.activeLocation == name ? null : _cameras.activeLocation, clubLocation: _cameras.clubLocation == name ? null : _cameras.clubLocation, )); } Future setPositionCount(int count) => _setCameras(_cameras.copyWith(positions: count.clamp(1, CameraSetup.maxPositions))); Future setCameraIp(int position, String location, String ip) { final ips = _cameras.ipsCopy(); (ips[position] ??= {})[location] = ip.trim(); return _setCameras(_cameras.copyWith(ips: ips)); } /// Points every position of [location] at one host with consecutive ports (9081, 9082, ...). Future setLocationHost(String location, String host) { final ips = _cameras.ipsCopy(); for (int p = 1; p <= _cameras.positions; p++) { (ips[p] ??= {})[location] = '$host:${CameraSetup.firstPort + p - 1}'; } return _setCameras(_cameras.copyWith(ips: ips)); } Future setActiveLocation(String location) => _setCameras(_cameras.copyWith(activeLocation: location)); // Club data may carry the club's cameras: {"cameras": {"location": "Kovinar", "ips": [...]}} Future _applyClubCameras(String plaintext) async { final data = (jsonDecode(plaintext) as Map)['cameras'] as Map?; if (data == null) return; final location = data['location'] as String; final clubIps = [for (final ip in data['ips'] as List) ip as String]; final ips = _cameras.ipsCopy(); for (int i = 0; i < clubIps.length && i < CameraSetup.maxPositions; i++) { (ips[i + 1] ??= {})[location] = clubIps[i]; } await _setCameras(_cameras.copyWith( locations: _cameras.locations.contains(location) ? null : [location, ..._cameras.locations], positions: clubIps.length.clamp(_cameras.positions, CameraSetup.maxPositions), ips: ips, activeLocation: _cameras.activeLocation ?? location, clubLocation: location, )); } /// Decrypts the bundled club data with [code]. Returns false if the code is wrong. Future unlockClub(String code) async { final encrypted = await _loadClubAsset(); if (encrypted == null) return false; // asset missing: run tool/encrypt_club_data.dart // Key derivation is deliberately slow; keep it off the UI thread final plaintext = await Isolate.run(() => ClubCrypto.decrypt(encrypted, code)); if (plaintext == null) return false; _clubContacts = _parseContacts(plaintext); notifyListeners(); await _applyClubCameras(plaintext); await _prefs.setString('clubData', plaintext); await _prefs.setString('clubCode', code); await _prefs.setString('clubDataSource', encrypted); return true; } Future lockClub() async { _clubContacts = null; notifyListeners(); final clubLocation = _cameras.clubLocation; if (clubLocation != null) await removeLocation(clubLocation); await _prefs.remove('clubData'); await _prefs.remove('clubCode'); await _prefs.remove('clubDataSource'); } /// If the bundled club.enc changed since unlocking (new app version), decrypt /// it again with the saved code. A changed club code locks the phone again. Future _refreshClubData() async { final encrypted = await _loadClubAsset(); final code = _prefs.getString('clubCode'); if (encrypted == null || encrypted == _prefs.getString('clubDataSource')) return; if (code == null || !await unlockClub(code)) await lockClub(); } static Future _loadClubAsset() async { try { return await rootBundle.loadString('assets/club.enc'); } catch (_) { return null; } } static List _parseContacts(String json) { final list = (jsonDecode(json) as Map)['contacts'] as List; return list.map((c) => Contact.fromJson(c as Map)).toList(); } }