import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:road24_mobile/data/repository/ChequeRepository.dart';
import 'package:road24_mobile/data/response/ChequeDetailsResponse.dart';
import 'package:road24_mobile/data/response/ChequeListResponse.dart';

part 'cheque_event.dart';

part 'cheque_state.dart';

class ChequeBloc extends Bloc<ChequeEvent, ChequeState> {
  final ChequeRepository repository;

  ChequeBloc({required this.repository}) : super(ChequeInitialState());

  @override
  Stream<ChequeState> mapEventToState(ChequeEvent event) async* {
    if (event is GetChequeList) {
      try {
        yield ChequeLoadingState();
        final dynamic response = await repository.getChequeList(
            page: event.page, pageSize: event.pageSize);
        yield ChequeListSuccessState(
            response: ChequeListResponse.fromJson(response));
      } catch (e) {
        yield ChequeErrorState(exception: e);
      }
    } else if (event is GetChequeDetails) {
      try {
        yield ChequeLoadingState();
        final dynamic response =
            await repository.getChequeDetailsById(event.id);
        yield ChequeDetailsSuccessState(
            response: ChequeDetailsResponse.fromJson(response));
      } catch (e) {
        yield ChequeErrorState(exception: e);
      }
    } else if (event is GetAllChequeList) {
      try {
        yield ChequeLoadingState();
        final dynamic response = await repository.getAllChequeList(
            page: event.page, pageSize: event.pageSize);
        yield ChequeListSuccessState(
            response: AllChequeListResponse.fromJson(response));
      } catch (e) {
        yield ChequeErrorState(exception: e);
      }
    }
  }
}
