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

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

  // properties
  int id;
  bool deleted;
  String value;
  bool forCarbsRatio;
  bool forPortionSize;
  int? confidenceRating;
  String? notes;

  // constructor
  Accuracy({
    this.id = 0,
    this.deleted = false,
    this.value = '',
    this.forCarbsRatio = false,
    this.forPortionSize = false,
    this.confidenceRating,
    this.notes,
  });

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

  static List<Accuracy> getAll() {
    QueryBuilder<Accuracy> all = box.query(Accuracy_.deleted.equals(false))
      ..order(Accuracy_.confidenceRating);
    return all.build().find();
  }

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

  static List<Accuracy> getAllForPortionSize() {
    QueryBuilder<Accuracy> allForPortionSize = box.query(
        Accuracy_.forPortionSize.equals(true) & Accuracy_.deleted.equals(false))
      ..order(Accuracy_.confidenceRating);
    return allForPortionSize.build().find();
  }

  static List<Accuracy> getAllForCarbsRatio() {
    QueryBuilder<Accuracy> allForCarbsRatio = box.query(
        Accuracy_.forCarbsRatio.equals(true) & Accuracy_.deleted.equals(false))
      ..order(Accuracy_.confidenceRating);
    return allForCarbsRatio.build().find();
  }

  static void reorder(Accuracy accuracy, int? newPosition) {
    QueryBuilder<Accuracy> all = box.query(Accuracy_.deleted.equals(false).and(Accuracy_.id.notEquals(accuracy.id)))
      ..order(Accuracy_.confidenceRating);
    List<Accuracy> accuracies = all.build().find();
    newPosition == null || newPosition >= accuracies.length ? accuracies.add(accuracy) : accuracies.insert(newPosition, accuracy);
    box.putMany(accuracies.map((item) {
      item.confidenceRating = accuracies.indexOf(item);
      return item;
    }).toList());
  }

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