import 'package:hive_flutter/hive_flutter.dart'; import '../models/cached_goal_model.dart'; class OfflineCacheService { static const String _goalsBoxName = 'cached_goals'; static const String _userBoxName = 'cached_user'; static const String _countdownBoxName = 'cached_countdown'; late Box _goalsBox; late Box _userBox; late Box _countdownBox; Future init() async { await Hive.initFlutter(); if (!Hive.isAdapterRegistered(0)) { Hive.registerAdapter(CachedGoalAdapter()); } _goalsBox = await Hive.openBox(_goalsBoxName); _userBox = await Hive.openBox(_userBoxName); _countdownBox = await Hive.openBox(_countdownBoxName); } Future cacheGoals(List goals) async { await _goalsBox.clear(); for (var goal in goals) { await _goalsBox.put(goal.id, goal); } } Future> getCachedGoals() async { return _goalsBox.values.toList(); } Future getCachedGoal(String goalId) async { return _goalsBox.get(goalId); } Future cacheGoal(CachedGoal goal) async { await _goalsBox.put(goal.id, goal); } Future deleteCachedGoal(String goalId) async { await _goalsBox.delete(goalId); } Future markGoalAsDirty(String goalId) async { final goal = _goalsBox.get(goalId); if (goal != null) { await _goalsBox.put(goalId, goal.copyWith(isDirty: true)); } } Future> getDirtyGoals() async { return _goalsBox.values.where((goal) => goal.isDirty).toList(); } Future clearDirtyFlag(String goalId) async { final goal = _goalsBox.get(goalId); if (goal != null) { await _goalsBox.put(goalId, goal.copyWith(isDirty: false)); } } Future cacheUserData(Map userData) async { await _userBox.putAll(userData); } Future> getCachedUserData() async { return Map.from(_userBox.toMap()); } Future cacheCountdownData(Map countdownData) async { await _countdownBox.putAll(countdownData); } Future> getCachedCountdownData() async { return Map.from(_countdownBox.toMap()); } Future clearAllCache() async { await _goalsBox.clear(); await _userBox.clear(); await _countdownBox.clear(); } Future close() async { await _goalsBox.close(); await _userBox.close(); await _countdownBox.close(); } }