import 'package:ambito/src/entity/area/area.dart';
import 'package:ambito/src/entity/cart/cart.dart';
import 'package:ambito/src/entity/entities.dart';
import 'package:ambito/src/entity/lists/list_measure.dart';
import 'package:ambito/src/entity/lists/list_measure_single.dart';
import 'package:ambito/src/entity/lists/list_measure_type_group_category.dart';
import 'package:ambito/src/entity/login/login.dart';
import 'package:ambito/src/entity/measure/category/measure_category.dart';
import 'package:ambito/src/entity/measure/complete/measure_complete.dart';
import 'package:ambito/src/entity/measure/details/measure_details.dart';
import 'package:ambito/src/entity/measure/group/measure_group.dart';
import 'package:ambito/src/entity/measure/measure_grouping.dart';
import 'package:ambito/src/entity/measure/months/measure_months.dart';
import 'package:ambito/src/entity/measure/types_details/measure_types_details.dart';
import 'package:flutter/foundation.dart';
import 'package:isar/isar.dart';
import 'package:path_provider/path_provider.dart';

import '../../consts/consts.dart';
import '../../entity/cart/cart_element.dart';
import '../../entity/measure/type/measure_type.dart';

export 'repositories/_repositories.dart';

class AmbitoIsarDB {
  static init() async {
    await Isar.initialize();
    String dir = kIsWeb
        ? Isar.sqliteInMemory
        : (await getApplicationDocumentsDirectory()).path;
    const engine = kIsWeb ? IsarEngine.sqlite : IsarEngine.isar;
    isar = Isar.open(
      schemas: [
        AreaSchema,
        ApprovalRequirementSchema,
        BusinessSchema,
        CartSchema,
        CartElementSchema,
        ExperienceReportSchema,
        FundingProgramSchema,
        ItemFilterSchema,
        ListMeasureSchema,
        ListMeasureSingleSchema,
        ListMeasureTypeGroupCategorySchema,
        LoginSchema,
        MaterialSchema,
        MeasureMonthsSchema,
        MeasureCompleteSchema,
        MeasureTypesSchema,
        MeasureTypesDetailsSchema,
        MeasureGeneralSchema,
        MeasureDetailsSchema,
        MeasureGroupSchema,
        MeasureCategorySchema,
        MeasureTypeSchema,
        MeasureGroupingSchema,
      ],
      directory: dir,
      engine: engine,
      inspector: true,
    );
  }
}

abstract class BaseDB {
  abstract IsarCollection collection;

  put(BaseEntity entity) {
    isar.write((isar) {
      collection.put(entity);
    });
  }

  putAll(List<BaseEntity> entities) {
    isar.write((isar) {
      collection.putAll(entities);
    });
  }

  // get entity by id
  BaseEntity get(int id) {
    return collection.get(id);
  }

  // get all entities of selected collection
  List<dynamic> getAll() {
    return collection.where().findAll();
  }

  delete(int id) {
    isar.write((isar) {
      collection.delete(id);
    });
  }
}
