import 'package:diameter/main.dart';
import 'package:diameter/models/log_bolus.dart';
import 'package:diameter/models/log_entry.dart';
import 'package:diameter/models/meal.dart';
import 'package:diameter/models/meal_category.dart';
import 'package:diameter/models/meal_portion_type.dart';
import 'package:diameter/models/meal_source.dart';
import 'package:diameter/models/accuracy.dart';
import 'package:objectbox/objectbox.dart';
import 'package:diameter/objectbox.g.dart' show LogMeal_, LogEntry_;

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

  // properties
  int id;
  bool deleted;
  String value;
  double? carbsRatio;
  double? portionSize;
  double? totalCarbs;
  String? notes;
  double? bolus;
  double amount;

  // relations
  final logEntry = ToOne<LogEntry>();
  final meal = ToOne<Meal>();
  final mealSource = ToOne<MealSource>();
  final mealCategory = ToOne<MealCategory>();
  final mealPortionType = ToOne<MealPortionType>();
  final portionSizeAccuracy = ToOne<Accuracy>();
  final carbsRatioAccuracy = ToOne<Accuracy>();

  // constructor
  LogMeal({
    this.id = 0,
    this.deleted = false,
    this.value = '',
    this.amount = 1,
    this.carbsRatio,
    this.portionSize,
    this.totalCarbs,
    this.notes,
  });

  // methods
  static LogMeal? get(int id) => box.get(id);
  static void put(LogMeal logMeal) => box.put(logMeal);
  static void remove(int id) {
    final item = box.get(id);
    if (item != null) {
      item.deleted = true;
      box.put(item);
    }
  }

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

  static List<LogMeal> getRecentWithoutBolus(int id) {
    final dateTime = LogEntry.get(id)?.time ?? DateTime.now();
    QueryBuilder<LogMeal> builder = box.query(LogMeal_.deleted.equals(false));
    builder.link(LogMeal_.logEntry);
    List<LogMeal> results = builder.build().find();
    results.retainWhere((logMeal) {
      final entryTime = logMeal.logEntry.target!.time;
      return entryTime.isAfter(dateTime.subtract(const Duration(hours: 12))) &&
          entryTime.isBefore(dateTime.add(const Duration(hours: 12))) && !LogBolus.bolusForMealExists(logMeal.id);
    });
    return results;
  }

  static double getTotalCarbsForEntry(int id) {
    QueryBuilder<LogMeal> builder = box.query(LogMeal_.deleted.equals(false));
    builder.link(LogMeal_.logEntry, LogEntry_.id.equals(id));
    return builder.build().property(LogMeal_.totalCarbs).sum();
  }

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