import 'package:bloc/bloc.dart';
import 'package:dartz/dartz.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:injectable/injectable.dart';

import '../../../domain/analytic/analytic.dart';

part 'payment_method_analytic_loader_event.dart';
part 'payment_method_analytic_loader_state.dart';
part 'payment_method_analytic_loader_bloc.freezed.dart';

@injectable
class PaymentMethodAnalyticLoaderBloc
    extends
        Bloc<
          PaymentMethodAnalyticLoaderEvent,
          PaymentMethodAnalyticLoaderState
        > {
  final IAnalyticRepository _analyticRepository;
  PaymentMethodAnalyticLoaderBloc(this._analyticRepository)
    : super(PaymentMethodAnalyticLoaderState.initial()) {
    on<PaymentMethodAnalyticLoaderEvent>(_onPaymentMethodAnalyticLoaderEvent);
  }

  Future<void> _onPaymentMethodAnalyticLoaderEvent(
    PaymentMethodAnalyticLoaderEvent event,
    Emitter<PaymentMethodAnalyticLoaderState> emit,
  ) {
    return event.map(
      fetched: (e) async {
        emit(state.copyWith(isFetching: true, failureOption: none()));

        final result = await _analyticRepository.getPaymentMethod(
          dateFrom: e.startDate,
          dateTo: e.endDate,
        );

        await result.fold(
          (failure) async {
            emit(
              state.copyWith(
                isFetching: false,
                failureOption: optionOf(failure),
              ),
            );
          },
          (paymentMethod) async {
            emit(
              state.copyWith(
                isFetching: false,
                paymentMethodAnalytic: paymentMethod,
              ),
            );
          },
        );
      },
    );
  }
}
