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 'category_analytic_loader_event.dart';
part 'category_analytic_loader_state.dart';
part 'category_analytic_loader_bloc.freezed.dart';

@injectable
class CategoryAnalyticLoaderBloc
    extends Bloc<CategoryAnalyticLoaderEvent, CategoryAnalyticLoaderState> {
  final IAnalyticRepository _analyticRepository;
  CategoryAnalyticLoaderBloc(this._analyticRepository)
    : super(CategoryAnalyticLoaderState.initial()) {
    on<CategoryAnalyticLoaderEvent>(_onCategoryAnalyticLoaderEvent);
  }

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

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

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