import 'package:diameter/main.dart';
import 'package:diameter/models/accuracy.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/objectbox.g.dart' show Meal_;
import 'package:objectbox/objectbox.dart';

enum PortionCarbsParameter { carbsRatio, portionSize, carbsPerPortion }

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

  // properties
  int id;
  bool deleted;
  String value;
  double? carbsRatio;
  double? portionSize;
  double? carbsPerPortion;
  int? delayedBolusDuration;
  double? delayedBolusPercentage;
  String? notes;

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

  // constructor
  Meal({
    this.id = 0,
    this.deleted = false,
    this.value = '',
    this.carbsRatio,
    this.portionSize,
    this.carbsPerPortion,
    this.delayedBolusDuration,
    this.delayedBolusPercentage,
    this.notes,
  });

  // methods
  static Meal? get(int id) => box.get(id);
  static void put(Meal meal) => box.put(meal);
  
  static List<Meal> getAll() {
     QueryBuilder<Meal> builder = box.query(Meal_.deleted.equals(false))..order(Meal_.value);
    return builder.build().find();
  }
  
  static void remove(int id) {
    final item = box.get(id);
    if (item != null) {
      item.deleted = true;
      box.put(item);
    }
  }

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