import 'package:diameter/main.dart';
import 'package:diameter/models/bolus.dart';
import 'package:diameter/models/log_entry.dart';
import 'package:diameter/models/log_meal.dart';
import 'package:objectbox/objectbox.dart';
import 'package:diameter/objectbox.g.dart' show LogBolus_, LogEntry_, LogMeal_;

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

  // properties
  int id;
  bool deleted;
  double units;
  double? carbs;
  int? delay;
  int? mgPerDlCurrent;
  int? mgPerDlTarget;
  int? mgPerDlCorrection;
  double? mmolPerLCurrent;
  double? mmolPerLTarget;
  double? mmolPerLCorrection;
  bool setManually;
  String? notes;

  // relations
  final logEntry = ToOne<LogEntry>();
  final rate = ToOne<Bolus>();
  final meal = ToOne<LogMeal>();

  // constructor
  LogBolus({
    this.id = 0,
    this.deleted = false,
    this.units = 0,
    this.carbs,
    this.delay,
    this.mgPerDlCurrent,
    this.mgPerDlTarget,
    this.mgPerDlCorrection,
    this.mmolPerLCurrent,
    this.mmolPerLTarget,
    this.mmolPerLCorrection,
    this.setManually = false,
    this.notes,
  });

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

  static List<LogBolus> getAllForEntry(int id) {
    QueryBuilder<LogBolus> builder = box.query(LogBolus_.deleted.equals(false));
    builder.link(LogBolus_.logEntry, LogEntry_.id.equals(id));
    return builder.build().find();
  }

  static double getTotalBolusForEntry(int id) {
    QueryBuilder<LogBolus> builder = box.query(LogBolus_.deleted.equals(false));
    builder.link(LogBolus_.logEntry, LogEntry_.id.equals(id));
    return builder.build().property(LogBolus_.units).sum();
  }

  static bool glucoseBolusForEntryExists(int id) {
    QueryBuilder<LogBolus> builder = box.query(LogBolus_.deleted
        .equals(false)
        .and(LogBolus_.mgPerDlCorrection.notNull()));
    builder.link(LogBolus_.meal, LogMeal_.id.equals(id));
    return builder.build().find().isNotEmpty;
  }

  static bool bolusForMealExists(int id) {
    QueryBuilder<LogBolus> builder = box.query(LogBolus_.deleted
        .equals(false));
    builder.link(LogBolus_.meal, LogMeal_.id.equals(id));
    return builder.build().find().isNotEmpty;
  }

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

  @override
  String toString() {
    return units.toString();
  }
}
