import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:road24_mobile/data/repository/NewsRepository.dart';
import 'package:road24_mobile/data/response/NewsResponse.dart';

part 'news_event.dart';

part 'news_state.dart';

class NewsBloc extends Bloc<NewsEvent, NewsState> {
  final NewsRepository repository;

  NewsBloc({required this.repository}) : super(NewsInitial());

  @override
  Stream<NewsState> mapEventToState(
    NewsEvent event,
  ) async* {
    if (event is NewsEvent) {
      try {
        yield NewsInitial();
        final dynamic response = await repository.getNews();
        yield GetNewsSuccessState(
          response: NewsResponse.fromJson(response),
        );
      } catch (e) {
        yield NewsLoadingError();
      }
    }

    if (event is ReadNewsEvent) {
      try {
        yield NewsInitial();
        final dynamic response = await repository.readNews(id: event.id);
        yield ReadNewsSuccessState(
          results: NewsResults.fromJson(response),
        );
      } catch (e) {
        yield NewsLoadingError();
      }
    }
  }
}
