|
| 1 | +import 'package:roboscout_iq/src/models/team_model.dart'; |
| 2 | +import 'package:roboscout_iq/src/services/api_client.dart'; |
| 3 | +import 'package:roboscout_iq/src/services/local_db_service.dart'; |
| 4 | + |
| 5 | +class LeaderboardRepository { |
| 6 | + final ApiClient _apiClient; |
| 7 | + final LocalDbService _localDb; |
| 8 | + |
| 9 | + LeaderboardRepository(this._apiClient, this._localDb); |
| 10 | + |
| 11 | + Future<List<Map<String, dynamic>>> getGlobalSkills(String gradeLevel, |
| 12 | + {bool forceRefresh = false}) async { |
| 13 | + final cacheKey = 'skills_$gradeLevel'; |
| 14 | + final box = _localDb.leaderboardBox; |
| 15 | + |
| 16 | + if (!forceRefresh && box.containsKey(cacheKey)) { |
| 17 | + try { |
| 18 | + final cachedData = box.get(cacheKey); |
| 19 | + if (cachedData is List) { |
| 20 | + return cachedData |
| 21 | + .map((e) => Map<String, dynamic>.from(e as Map)) |
| 22 | + .toList(); |
| 23 | + } |
| 24 | + } catch (e) { |
| 25 | + print('Error reading skills cache: $e'); |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + try { |
| 30 | + final data = await _apiClient.getGlobalSkills(gradeLevel: gradeLevel); |
| 31 | + await box.put(cacheKey, data); |
| 32 | + return data; |
| 33 | + } catch (e) { |
| 34 | + if (box.containsKey(cacheKey)) { |
| 35 | + final cachedData = box.get(cacheKey); |
| 36 | + if (cachedData is List) { |
| 37 | + return cachedData |
| 38 | + .map((e) => Map<String, dynamic>.from(e as Map)) |
| 39 | + .toList(); |
| 40 | + } |
| 41 | + } |
| 42 | + rethrow; |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + Future<List<Team>> getGlobalTrueSkillRankings( |
| 47 | + {bool forceRefresh = false}) async { |
| 48 | + const cacheKey = 'trueskill_global'; |
| 49 | + final box = _localDb.leaderboardBox; |
| 50 | + |
| 51 | + if (!forceRefresh && box.containsKey(cacheKey)) { |
| 52 | + try { |
| 53 | + final cachedData = box.get(cacheKey); |
| 54 | + if (cachedData is List) { |
| 55 | + return _deserializeTeams(cachedData); |
| 56 | + } |
| 57 | + } catch (e) { |
| 58 | + print('Error reading trueskill cache: $e'); |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + try { |
| 63 | + final teams = await _apiClient.getGlobalTrueSkillRankings(); |
| 64 | + final jsonList = teams.map((t) => t.toJson()).toList(); |
| 65 | + await box.put(cacheKey, jsonList); |
| 66 | + return teams; |
| 67 | + } catch (e) { |
| 68 | + if (box.containsKey(cacheKey)) { |
| 69 | + final cachedData = box.get(cacheKey) as List; |
| 70 | + return _deserializeTeams(cachedData); |
| 71 | + } |
| 72 | + rethrow; |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + List<Team> _deserializeTeams(List<dynamic> list) { |
| 77 | + return list.map((e) { |
| 78 | + // Hive returns _Map<dynamic, dynamic>, need to cast to Map<String, dynamic> |
| 79 | + // for Team.fromJson |
| 80 | + final json = Map<String, dynamic>.from(e as Map); |
| 81 | + return Team.fromJson(json); |
| 82 | + }).toList(); |
| 83 | + } |
| 84 | +} |
0 commit comments