import 'package:diameter/main.dart';
import 'package:objectbox/objectbox.dart';
import 'package:diameter/objectbox.g.dart' show MealCategory_;

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

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

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

  // methods
  static MealCategory? get(int id) => box.get(id);
  static void put(MealCategory mealCategory) => box.put(mealCategory);
  
  static List<MealCategory> getAll() {
    QueryBuilder<MealCategory> builder = box.query(MealCategory_.deleted.equals(false))..order(MealCategory_.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;
    return data;
  }

  static String? putFromJson(
      Map<String, dynamic> json, bool overrideExisting, String? source) {
    final mealCategory = MealCategory(
      id: overrideExisting ? json['id'] : 0,
      deleted: json['deleted'] == 'true',
      value: json['value'],
      notes: json['notes'],
      source: source,
    );
    
    MealCategory.put(mealCategory);
    return null;
  }
}
