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

import '../../../domain/analytic/analytic.dart';
import '../../../domain/analytic/repositories/i_analytic_repository.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 _repository;
  PaymentMethodAnalyticLoaderBloc(this._repository)
    : super(PaymentMethodAnalyticLoaderState.initial()) {
    on<PaymentMethodAnalyticLoaderEvent>(_onPaymentMethodAnalyticLoaderEvent);
  }

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

        final result = await _repository.getPaymentMethod(
          dateFrom: state.dateFrom,
          dateTo: state.dateTo,
        );

        var data = result.fold(
          (f) =>
              state.copyWith(failureOptionPaymentMethodAnalytic: optionOf(f)),
          (paymentMethodAnalytic) =>
              state.copyWith(paymentMethodAnalytic: paymentMethodAnalytic),
        );

        emit(data.copyWith(isFetching: false));
      },
    );
  }
}
