import 'package:ambito/src/entity/entities.dart';
import 'package:ambito/src/entity/measure/general/measure_general.dart';
import 'package:ambito/src/extensions/extensions.dart';
import 'package:isar/isar.dart';

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

class MeasureGeneralRepository extends BaseDB {
  @override
  IsarCollection collection = isar.measureGenerals;

  List<MeasureGeneral> getAllOrdered() {
    return isar.measureGenerals.where().sortByName().findAll();
  }

  MeasureGeneral? getByName(String name) {
    return isar.measureGenerals.where().nameEqualTo(name).findFirst();
  }

  List<MeasureGeneral> getAllOrderedByGroupAndType(
    String group,
    String type,
  ) {
    final lowerCaseGroup = group.toLowerCase().replaceUmlauts();
    final lowerCaseType = type.toLowerCase().replaceUmlauts();

    final all = isar.measureGenerals.where().sortByName().findAll();

    return all.where((mg) {
      final groupMatches = mg.measureGroup?.any((idvm) =>
              idvm.value?.value?.toLowerCase().replaceUmlauts() ==
              lowerCaseGroup) ??
          false;

      final typeMatches = mg.measureType?.any((idv) =>
              idv.value?.toLowerCase().replaceUmlauts() == lowerCaseType) ??
          false;

      return groupMatches || typeMatches;
    }).toList();
  }
}
