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 'profit_loss_analytic_loader_event.dart';
part 'profit_loss_analytic_loader_state.dart';
part 'profit_loss_analytic_loader_bloc.freezed.dart';

@injectable
class ProfitLossAnalyticLoaderBloc
    extends Bloc<ProfitLossAnalyticLoaderEvent, ProfitLossAnalyticLoaderState> {
  final IAnalyticRepository _analyticRepository;
  ProfitLossAnalyticLoaderBloc(this._analyticRepository)
    : super(ProfitLossAnalyticLoaderState.initial()) {
    on<ProfitLossAnalyticLoaderEvent>(_onProfitLossAnalyticLoaderEvent);
  }

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

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

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