getLongestStreak method
- String userEmail,
- BuildContext context
Retrieves the user's longest streak, either active or completed.
Returns a map with the duration in days, start date, and end date (or "active" if the streak is ongoing).
Implementation
Future<Map<String, dynamic>?> getLongestStreak(
String userEmail, BuildContext context) async {
final localizations = AppLocalizations.of(context)!;
final userRef = await _getUserDocRef(userEmail);
final allStreaksSnapshot = await userRef.collection('streaks').get();
if (allStreaksSnapshot.docs.isEmpty) return null;
int maxDays = 0;
DateTime? longestStart;
DateTime? longestEnd;
bool isActiveStreak = false;
for (var doc in allStreaksSnapshot.docs) {
final startedAt = (doc['startedAt'] as Timestamp).toDate();
DateTime endDate;
final bool isActive = doc['isActive'] == true;
if (doc['isActive'] == true) {
endDate = DateTime.now();
} else {
endDate = (doc['failedAt'] as Timestamp).toDate();
}
final duration = endDate.difference(startedAt).inDays + 1;
if (duration > maxDays) {
maxDays = duration;
longestStart = startedAt;
longestEnd = endDate;
isActiveStreak = isActive;
}
}
return {
'lengthInDays': maxDays,
'startDate': _formatDate(longestStart!),
'endDate': isActiveStreak
? localizations.tStreakStillActive
: _formatDate(longestEnd!),
};
}