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

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

  // properties
  int id;
  bool deleted;
  @Unique()
  String value;
  String? notes;
  String? source;

  // relations
  final defaultMealCategory = ToOne<MealCategory>();
  final defaultMealPortionType = ToOne<MealPortionType>();
  final defaultCarbsRatioAccuracy = ToOne<Accuracy>();
  final defaultPortionSizeAccuracy = ToOne<Accuracy>();

  // constructor
  MealSource({
    this.id = 0,
    this.deleted = false,
    this.value = '',
    this.notes,
    this.source,
  });

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

  static List<MealSource> getAll() {
    QueryBuilder<MealSource> builder =
        box.query(MealSource_.deleted.equals(false))..order(MealSource_.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;
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['id'] = id;
    data['deleted'] = deleted;
    data['value'] = value;
    data['notes'] = notes;
    data['defaultMealCategory'] = defaultMealCategory.targetId;
    data['defaultMealPortionType'] = defaultMealPortionType.targetId;
    data['defaultCarbsRatioAccuracy'] = defaultCarbsRatioAccuracy.targetId;
    data['defaultPortionSizeAccuracy'] = defaultPortionSizeAccuracy.targetId;
    return data;
  }

  static String? putFromJson(
      Map<String, dynamic> json, bool overrideExisting, String? source) {
    final mealSource = MealSource(
      id: overrideExisting ? json['id'] : 0,
      deleted: json['deleted'] == 'true',
      value: json['value'],
      notes: json['notes'],
      source: source,
    );

    mealSource.defaultMealCategory.targetId = json['defaultMealCategory'];
    mealSource.defaultMealPortionType.targetId = json['defaultMealPortionType'];
    mealSource.defaultCarbsRatioAccuracy.targetId = json['defaultCarbsRatioAccuracy'];
    mealSource.defaultPortionSizeAccuracy.targetId = json['defaultPortionSizeAccuracy'];

    MealSource.put(mealSource);
    return null;
  }
}
