import 'package:fitnote/models/health.dart'; import 'package:fitnote/utils/record_utils.dart'; import 'package:flutter_common/flutter_common.dart'; import 'package:hive_flutter/hive_flutter.dart'; class HealthService { static const String boxName = 'healths'; Box get box => Hive.box(boxName); Future addRecord(HealthRecord record) async { try { await box.add(record); return true; } catch (e) { return false; } } List getAllRecords() { return box.values.toList(); } HealthRecord getRecordByDate(DateTime date) { final record = box.values.toList().firstWhere( (item) => item.date == formatDate(date), orElse: () => HealthRecord.getEmpty(date), ); return record.copyWith(); } num getTotalSport() { int year = DateTime.now().year; int month = DateTime.now().month; num totalDuration = 0; for (final record in getAllRecords()) { if (record.sportDuration != 0) { final recordDate = DateTime.parse(record.date); if (recordDate.year == year && recordDate.month == month) { totalDuration += record.sportDuration; } } } return totalDuration; } num getAvgSleep() { int year = DateTime.now().year; int month = DateTime.now().month; num totalDuration = 0; int total = 0; for (final record in getAllRecords()) { final startTime = record.sleepStartTime; final endTime = record.sleepEndTime; if (startTime.isNotEmpty && endTime.isNotEmpty) { final recordDate = DateTime.parse(record.date); if (recordDate.year == year && recordDate.month == month) { total++; totalDuration += calSleepMinuteDuration(startTime, endTime); } } } if (totalDuration == 0) { return 0; } else { return roundNum(totalDuration / total / 60); } } num getLatestWeight() { final records = getAllRecords(); records.sort((a, b) { final dateA = DateTime.parse(a.date); final dateB = DateTime.parse(b.date); return dateB.compareTo(dateA); }); for (final record in records) { if (record.weight != 0) { return record.weight; } } return 0; } Future updateRecord(HealthRecord record) async { try { List records = box.values.where((item) => item.date == record.date).toList(); if (records.isEmpty) { await addRecord(record); } else { await record.save(); } return true; } catch (e) { return false; } } Future deleteRecord(HealthRecord record) async { try { await record.delete(); return true; } catch (e) { return false; } } }