import 'package:diameter/main.dart'; import 'package:diameter/models/bolus.dart'; import 'package:diameter/models/log_event.dart'; import 'package:objectbox/objectbox.dart'; import 'package:diameter/objectbox.g.dart' show BolusProfile_; @Entity(uid: 8812452529027052317) @Sync() class BolusProfile { static final Box box = objectBox.store.box(); // properties int id; bool deleted; @Unique() String name; bool active; String? notes; String? source; // constructor BolusProfile({ this.id = 0, this.deleted = false, this.name = '', this.active = false, this.notes, this.source, }); // methods static BolusProfile? get(int id) => box.get(id); static void put(BolusProfile bolusProfile) => box.put(bolusProfile); static List getAll() { QueryBuilder all = box.query(BolusProfile_.deleted.equals(false))..order(BolusProfile_.name); return all.build().find(); } static void remove(int id) { final item = box.get(id); if (item != null) { item.deleted = true; Bolus.removeAllForProfile(id); box.put(item); } } static int activeCount() { Query query = box .query(BolusProfile_.active .equals(true) .and(BolusProfile_.deleted.equals(false))) .build(); return query.find().length; } static void setAllInactive() { box.putMany(box.getAll().map((element) { element.active = false; return element; }).toList()); } static BolusProfile? getActive(DateTime? dateTime) { if (dateTime != null) { List activeEvents = LogEvent.getAllActiveForTime(dateTime) .where((event) => event.bolusProfile.target != null).toList(); if (activeEvents.length > 1) { final now = DateTime.now(); activeEvents = activeEvents.where((item) => !activeEvents.any((other) => item.time.isBefore(other.time) || (item.endTime ?? now).isAfter(other.endTime ?? now) )).toList(); } if (activeEvents.length == 1) { return activeEvents.single.bolusProfile.target; } } Query query = box .query(BolusProfile_.active .equals(true) .and(BolusProfile_.deleted.equals(false))) .build(); final result = query.find(); return result.length != 1 ? null : result.single; } @override String toString() { return name; } Map toJson() { final Map data = {}; data['id'] = id; data['deleted'] = deleted; data['name'] = name; data['active'] = active; data['notes'] = notes; return data; } static String? putFromJson( Map json, bool overrideExisting, String? source) { final bolusProfile = BolusProfile( id: overrideExisting ? json['id'] : 0, deleted: json['deleted'] == 'true', name: json['name'], active: json['active'], notes: json['notes'], source: source, ); BolusProfile.put(bolusProfile); return null; } }