import 'package:ambito/src/entity/cart/cart.dart';
import 'package:ambito/src/entity/cart/cart_element.dart';
import 'package:ambito/src/packages/ambito_notifier/notifier/cart_notifier.dart';
import 'package:isar/isar.dart';

import '../../consts/consts.dart';
import '../../packages/ambito_db/base_db.dart';

class CartRepository extends BaseDB {
  @override
  IsarCollection collection = isar.carts;

  void upsert(Cart cart) {
    Cart? existing = isar.carts.where().nameEqualTo(cart.name!).findFirst();

    if (existing == null) {
      ambitoCartNotifier.addCart();
      existing = cart;
    }
    isar.write((isar) {
      isar.carts.put(existing!);
    });
  }

  void putElement(CartElement cartElement) {
    isar.write((isar) {
      isar.cartElements.put(cartElement);
    });
  }

  List<Cart> getMyCarts() {
    List<Cart> myCarts = [];
    final all = isar.carts.where().findAll();
    for (final cart in all) {
      if (cart.business?.first.id == (prefs.getInt('currentUser') ?? 100)) {
        myCarts.add(cart);
      }
    }
    return myCarts;
  }

  List<CartElement> getElementsByCartId(int cartId) {
    List<CartElement> myElements = [];
    final all = isar.cartElements.where().findAll();
    for (final element in all) {
      if (element.cart!.first.id == cartId) {
        myElements.add(element);
      }
    }
    return myElements;
  }
}
