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 '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 _repository;

  CategoryAnalyticLoaderBloc(this._repository)
    : super(CategoryAnalyticLoaderState.initial()) {
    on<CategoryAnalyticLoaderEvent>(_onCategoryAnalyticLoaderEvent);
  }

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

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

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

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