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 'profit_loss_loader_event.dart';
part 'profit_loss_loader_state.dart';
part 'profit_loss_loader_bloc.freezed.dart';

@injectable
class ProfitLossLoaderBloc
    extends Bloc<ProfitLossLoaderEvent, ProfitLossLoaderState> {
  final IAnalyticRepository _repository;
  ProfitLossLoaderBloc(this._repository)
    : super(ProfitLossLoaderState.initial()) {
    on<ProfitLossLoaderEvent>(_onProfitLossLoaderEvent);
  }

  Future<void> _onProfitLossLoaderEvent(
    ProfitLossLoaderEvent event,
    Emitter<ProfitLossLoaderState> emit,
  ) {
    return event.map(
      rangeDateChanged: (e) async {
        emit(state.copyWith(dateFrom: e.dateFrom, dateTo: e.dateTo));
      },
      fetched: (e) async {
        emit(state.copyWith(isFetching: true, failureOptionProfitLoss: none()));

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

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

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