mirrored_repositories/Cinemapedia-Flutter/lib/infraestructure
import 'package:cinemapedia/domain/datasources/local_storage_datasource.dart';
import 'package:cinemapedia/domain/entities/movie.dart';
import 'package:isar/isar.dart';
import 'package:path_provider/path_provider.dart';


class IsarDatasource extends LocalStorageDatasource {

  late Future<Isar> db;

  IsarDatasource() {
    db = openDB();
  }

  Future<Isar> openDB() async {
    if (Isar.instanceNames.isEmpty) {
      final dir = await getApplicationDocumentsDirectory(); // this
      return await Isar.open(
        [MovieSchema], 
        inspector: true,
        directory: dir.path, // and this
      );
    }
    return Future.value(db);
  }

  @override
  Future<bool> isMovieFavorite(int movieId) async {

    final isar = await db;

    final Movie? movieFavorite = await isar.movies
      .filter()
      .idEqualTo(movieId)
      .findFirst();
    
    return movieFavorite != null;
  }

  @override
  Future<List<Movie>> loadMovies({int limit = 10, offset = 0}) async {
    final isar = await db;
    return isar.movies.where()
      .offset(offset)
      .limit(limit)
      .findAll();
  }

  @override
  Future<void> toggleFavorite(Movie movie) async {
    final isar = await db;
    
    final favoriteMovie = await isar.movies
      .filter()
      .idEqualTo(movie.id)
      .findFirst();
    
    if ( favoriteMovie != null ) {
      // Erase
      isar.writeTxnSync(() => isar.movies.deleteSync(favoriteMovie.idIsar!));
      return;
    }
    // Register
    isar.writeTxnSync(() => isar.movies.putSync(movie));
    // isar.movies.put(movie);
  }

}