import 'package:diameter/main.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<BolusProfile> box = objectBox.store.box<BolusProfile>();

  // properties
  int id;
  bool deleted;
  String name;
  bool active;
  String? notes;

  // constructor
  BolusProfile({
    this.id = 0,
    this.deleted = false,
    this.name = '',
    this.active = false,
    this.notes,
  });

  // methods
  static BolusProfile? get(int id) => box.get(id);
  static void put(BolusProfile bolusProfile) => box.put(bolusProfile);

  static List<BolusProfile> getAll() {
    QueryBuilder<BolusProfile> 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;
      box.put(item);
    }
  }

  static int activeCount() {
    Query<BolusProfile> 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<LogEvent> 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<BolusProfile> 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;
  }
}
