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'; Box? _goalsBox; Box? _userBox; Box? _countdownBox; Future init() async { try { 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); } catch (e) { print('Error initializing offline cache: $e'); } } Future cacheGoals(List goals) async { if (_goalsBox == null) return; await _goalsBox!.clear(); for (var goal in goals) { await _goalsBox!.put(goal.id, goal); } } Future> getCachedGoals() async { if (_goalsBox == null) return []; return _goalsBox!.values.toList(); } Future getCachedGoal(String goalId) async { if (_goalsBox == null) return null; return _goalsBox!.get(goalId); } Future cacheGoal(CachedGoal goal) async { if (_goalsBox == null) return; await _goalsBox!.put(goal.id, goal); } Future deleteCachedGoal(String goalId) async { if (_goalsBox == null) return; await _goalsBox!.delete(goalId); } Future markGoalAsDirty(String goalId) async { if (_goalsBox == null) return; final goal = _goalsBox!.get(goalId); if (goal != null) { await _goalsBox!.put(goalId, goal.copyWith(isDirty: true)); } } Future> getDirtyGoals() async { if (_goalsBox == null) return []; return _goalsBox!.values.where((goal) => goal.isDirty).toList(); } Future clearDirtyFlag(String goalId) async { if (_goalsBox == null) return; final goal = _goalsBox!.get(goalId); if (goal != null) { await _goalsBox!.put(goalId, goal.copyWith(isDirty: false)); } } Future cacheUserData(Map userData) async { if (_userBox == null) return; await _userBox!.putAll(userData); } Future> getCachedUserData() async { if (_userBox == null) return {}; return Map.from(_userBox!.toMap()); } Future cacheCountdownData(Map countdownData) async { if (_countdownBox == null) return; await _countdownBox!.putAll(countdownData); } Future> getCachedCountdownData() async { if (_countdownBox == null) return {}; return Map.from(_countdownBox!.toMap()); } Future clearAllCache() async { if (_goalsBox != null) await _goalsBox!.clear(); if (_userBox != null) await _userBox!.clear(); if (_countdownBox != null) await _countdownBox!.clear(); } Future close() async { if (_goalsBox != null) await _goalsBox!.close(); if (_userBox != null) await _userBox!.close(); if (_countdownBox != null) await _countdownBox!.close(); } }