import 'package:diameter/main.dart';
import 'package:diameter/models/basal_profile.dart';
import 'package:diameter/utils/date_time_utils.dart';
import 'package:objectbox/objectbox.dart';
import 'package:diameter/objectbox.g.dart' show Basal_, BasalProfile_;

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

  // properties
  int id;
  bool deleted;
  @Property(type: PropertyType.date)
  DateTime startTime;
  @Property(type: PropertyType.date)
  DateTime endTime;
  double units;

  // relations
  final basalProfile = ToOne<BasalProfile>();

  // constructor
  Basal({
    this.id = 0,
    this.deleted = false,
    required this.startTime,
    required this.endTime,
    this.units = 0,
  });

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

  static void remove(int id) {
    final item = box.get(id);
    if (item != null) {
      item.deleted = true;
      box.put(item);
    }
  }

  static List<Basal> getAllForProfile(int id) {
    QueryBuilder<Basal> builder = box.query(Basal_.deleted.equals(false))
      ..order(Basal_.startTime);
    builder.link(Basal_.basalProfile, BasalProfile_.id.equals(id));
    return builder.build().find();
  }

  static double getDailyTotalForProfile(int id) {
    double sum = 0.0;

    QueryBuilder<Basal> builder = box.query(Basal_.deleted.equals(false));
    builder.link(Basal_.basalProfile, BasalProfile_.id.equals(id));

    List<Basal> basalRates = builder.build().find();
    for (Basal basal in basalRates) {
      double rateDuration =
          basal.endTime.difference(basal.startTime).inMinutes / 60;
      if (rateDuration < 0) {
        rateDuration += 24;
      }
      sum += basal.units * rateDuration;
    }

    return sum;
  }

  @override
  String toString() {
    return DateTimeUtils.displayTime(startTime);
  }
}
