import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:habitrack_app/main.dart';
import 'package:habitrack_app/sembast/global_providers.dart';
import 'package:habitrack_app/sembast/hydration.dart';
import 'package:habitrack_app/sembast/item_repository.dart';
import 'package:habitrack_app/sembast/tasks_list.dart';
import 'package:habitrack_app/sembast/timer.dart';
import 'package:sembast/sembast.dart';

final itemRepositoryProvider = Provider(
  (ref) => SembastItemRepository(
    database: ref.watch(databaseProvider),
  ),
);

class SembastItemRepository implements ItemRepository {
  SembastItemRepository({required this.database}) {
    _store = intMapStoreFactory.store('item_store');
  }
  final Database database;
  late final StoreRef<int, Map<String, dynamic>> _store;

  @override
  Future<int> insertItem(dynamic item) {
    if (item is Hydration) {
      _store.add(database, item.toJson());
    } else if (item is TimerItem) {
      _store.add(database, item.toJson());
    } else if (item is TasksItem) {
      _store.add(database, item.toJson());
    }
    return Future.value(0);
  }

  @override
  Future<void> updateItem(dynamic item) {
    if (item is Hydration) {
      _store.record(item.id).update(database, item.toJson());
    } else if (item is TimerItem) {
      _store.record(item.id).update(database, item.toJson());
    } else if (item is TasksItem) {
      logger.i('UPDATING TASKS ITEM');
      _store.record(item.id).update(database, item.toJson());
    }
    logger.i('Item got past update: $item');
    return Future.value();
    //  throw Error();
  }

  @override
  Future<void> deleteItem(int itemId) => _store.record(itemId).delete(database);

  @override
  Stream<List<dynamic>> getAllItemsStream() =>
      _store.query().onSnapshots(database).map(
            (snapshot) => snapshot.map((item) {
              logger.i('Querying the database! ${item.value}');
              if (item.value.toString().contains('widgetType: Hydration')) {
                logger.i('Le hydration has arrived');

                return Hydration.fromJson(item.value).copyWith(id: item.key);
              } else if (item.value.toString().contains('widgetType: Timer')) {
                logger.i('Le timer has arrived');
                return TimerItem.fromJson(item.value).copyWith(id: item.key);
              } else if (item.value.toString().contains('widgetType: TODO')) {
                logger.i('Le TODO has arrived');
                return TasksItem.fromJson(item.value).copyWith(id: item.key);
              }
            }).toList(growable: false),
          );
}
