import 'package:diameter/main.dart';
import 'package:diameter/models/ingredient.dart';
import 'package:diameter/models/meal.dart';
import 'package:diameter/utils/utils.dart';
import 'package:objectbox/objectbox.dart';
import 'package:diameter/objectbox.g.dart' show Recipe_;

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

  // properties
  int id;
  bool deleted;
  String name;
  double? servings;
  String? notes;

  // relations
  final portion = ToOne<Meal>();

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

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

  static List<Recipe> getAll() {
    QueryBuilder<Recipe> builder = box.query(Recipe_.deleted.equals(false))
      ..order(Recipe_.name);
    return builder.build().find();
  }

  static double? getCarbsPerPortion(int id) {
    final servings = Recipe.get(id)?.servings;
    final totalWeight = Ingredient.getTotalWeightForRecipe(id);
    final carbsRatio = Ingredient.getCarbsRatioForRecipe(id);

    if (servings != null && totalWeight != null && carbsRatio != null) {
      final portionSize = totalWeight / servings;
      return Utils.calculateCarbs(carbsRatio, portionSize);
    }
    return null;
  }

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

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