import 'package:diameter/main.dart';
import 'package:diameter/models/log_event.dart';
import 'package:objectbox/objectbox.dart';
import 'package:diameter/objectbox.g.dart' show BasalProfile_;

@Entity(uid: 3613736032926903785)
@Sync()
class BasalProfile {
  static final Box<BasalProfile> box = objectBox.store.box<BasalProfile>();

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

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

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

  static List<BasalProfile> getAll() {
    QueryBuilder<BasalProfile> all = box.query(BasalProfile_.deleted.equals(false))
      ..order(BasalProfile_.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<BasalProfile> query = box
      .query(BasalProfile_.active.equals(true) & BasalProfile_.deleted.equals(false)).build();
    return query.find().length;
  }

  static void setAllInactive() {
    box.putMany(box.getAll().map((item) {
      item.active = false;
      return item;
    }).toList());
  }

  static BasalProfile? getActive(DateTime? dateTime) {
    if (dateTime != null) {
      List<LogEvent> activeEvents = LogEvent.getAllActiveForTime(dateTime)
          .where((event) => event.basalProfile.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.basalProfile.target;
      }
    }

    Query<BasalProfile> query = box
        .query(BasalProfile_.active
            .equals(true)
            .and(BasalProfile_.deleted.equals(false)))
        .build();
    final result = query.find();
    return result.length != 1 ? null : result.single;
  }

  @override
  String toString() {
    return name;
  }
}
