import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:road24_mobile/data/repository/NotificationsRepository.dart';
import 'package:road24_mobile/data/response/NotificationsResponse.dart';

part 'notifications_event.dart';
part 'notifications_state.dart';

class NotificationsBloc extends Bloc<NotificationsEvent, NotificationsState> {
  final NotificationRepository repository;
  NotificationsBloc({required this.repository}) : super(NotificationsInitial());

  @override
  Stream<NotificationsState> mapEventToState(
    NotificationsEvent event,
  ) async* {
    if (event is GetNotificationsEvent) {
      print("sent");
      try {
        yield NotificationsInitial();
        final dynamic response = await repository.getNotifications(
            page: event.page, pageSize: event.pageSize);
        print("here response:..$response");
        yield GetNotificationsSuccessState(
            response: NotificationResponse.fromJson(response));
      } catch (e) {
        print("notif error $e");
        yield NotificationLoadingError(e);
      }
    }
    if (event is GetNotificationDetailsEvent) {
      try {
        yield NotificationsInitial();
        final dynamic response =
            await repository.getNotificationDetails(event.id);
        var data = response["data"];
        print("here response:..$response");
        yield GetNotificationsDetailsSuccessState(markdownStr: data);
      } catch (e) {
        print("notif details error $e");
        yield NotificationLoadingError(e);
      }
    }

    if (event is GetUnreadNotificationsCountEvent) {
      try {
        yield NotificationsInitial();
        final dynamic response = await repository.getUnreadNotificationsCount();
        yield GetUnreadNotificationsCountSuccessState(
            response: UnreadNotificationsCountResponse.fromJson(response));
      } catch (e) {
        yield NotificationLoadingError(e);
      }
    }

    if (event is UserReadNotificationEvent) {
      try {
        yield NotificationsInitial();
        final dynamic result = await repository.userReadNotification(event.id);
        yield UserReadNotificationState(result: result);
      } catch (e) {
        yield NotificationLoadingError(e);
      }
    }
  }
}
