import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:road24_mobile/data/repository/CardRepository.dart';
import 'package:road24_mobile/data/response/GetCardResponse.dart';
import 'package:road24_mobile/view/settings/card/cards_page.dart';
part 'card_event.dart';
part 'card_state.dart';

class CardBloc extends Bloc<CardEvent, CardState> {
  final CardRepository repository;

  CardBloc({required this.repository}) : super(CardInitial());

  @override
  Stream<CardState> mapEventToState(
    CardEvent event,
  ) async* {
    if (event is AddCardEvent) {
      try {
        yield CardInitial();
        final response = await repository.addCard(
          cardNumber: event.cardNumber,
          expire: event.expire,
          name: event.name,
        );
        yield AddCardSuccessState(CardResults.fromJson(response));
      } catch (e) {
        yield CardLoadingError(exception: e);
      }
    }

    if (event is DeleteCardEvent) {
      try {
        yield CardInitial();
        await repository.deleteCard(event.id);
        CardsPage.cards.removeWhere((element) => element.id == event.id);
        yield DeleteCardSuccessState();
      } catch (e) {
        yield CardLoadingError(exception: e);
      }
    }

    if (event is GetCardEvent) {
      try {
        yield CardInitial();
        CardResults results = await repository.getCardById(event.id);
        yield GetCardSuccessState(response: results);
      } catch (e) {
        yield CardLoadingError(exception: e);
      }
    }

    if (event is GetCardsEvent) {
      try {
        yield CardInitial();
        final response = await repository.getCards();
        yield GetCardsSuccessState(
          response: GetCardsResponse.fromJson(response),
        );
      } catch (e) {
        yield CardLoadingError(exception: e);
      }
    }

    if (event is VerifyCardEvent) {
      try {
        yield CardInitial();
        await repository.verify(event.id, code: event.code);
        yield CardIsVerifiedSuccessState();
      } catch (e) {
        yield CardLoadingError(exception: e);
      }
    }

    if (event is ResendVerificationCodeEvent) {
      try {
        yield CardInitial();
        await repository.resendSmsCode(event.id);
        yield VerificationCodeResent();
      } catch (e) {
        yield CardLoadingError(exception: e);
      }
    }
  }
}
