import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:matrix/matrix.dart';
import 'package:pyramid/core/matrix_client.dart';

final roomListProvider = StreamProvider<List<Room>>((ref) async* {
  final client = await ref.watch(matrixClientProvider.future);

  yield _sortedRooms(client);

  await for (final _ in client.onSync.stream) {
    yield _sortedRooms(client);
  }
});

final dmUnreadCountProvider = StreamProvider<int>((ref) async* {
  final client = await ref.watch(matrixClientProvider.future);

  yield _countDmUnread(client);

  await for (final _ in client.onSync.stream) {
    yield _countDmUnread(client);
  }
});

int _countDmUnread(Client client) {
  return client.rooms
      .where((r) => !r.isSpace && r.isDirectChat && r.notificationCount > 0)
      .length;
}

List<Room> _sortedRooms(Client client) {
  final rooms = client.rooms
      .where((r) => !r.isSpace)
      .toList()
    ..sort((a, b) {
      final aTime = a.lastEvent?.originServerTs ?? DateTime(0);
      final bTime = b.lastEvent?.originServerTs ?? DateTime(0);
      return bTime.compareTo(aTime);
    });
  return rooms;
}
