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 'exclusive_summary_loader_event.dart';
part 'exclusive_summary_loader_state.dart';
part 'exclusive_summary_loader_bloc.freezed.dart';

@injectable
class ExclusiveSummaryLoaderBloc
    extends Bloc<ExclusiveSummaryLoaderEvent, ExclusiveSummaryLoaderState> {
  final IAnalyticRepository _repository;

  ExclusiveSummaryLoaderBloc(this._repository)
      : super(ExclusiveSummaryLoaderState.initial()) {
    on<ExclusiveSummaryLoaderEvent>(_onEvent);
  }

  Future<void> _onEvent(
    ExclusiveSummaryLoaderEvent event,
    Emitter<ExclusiveSummaryLoaderState> emit,
  ) {
    return event.map(
      rangeDateChanged: (e) async {
        emit(state.copyWith(dateFrom: e.dateFrom, dateTo: e.dateTo));
      },
      fetched: (e) async {
        emit(
          state.copyWith(
            isFetching: true,
            failureOption: none(),
          ),
        );

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

        final data = result.fold(
          (f) => state.copyWith(failureOption: optionOf(f)),
          (summary) => state.copyWith(exclusiveSummary: summary),
        );

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