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 'product_analytic_loader_event.dart';
part 'product_analytic_loader_state.dart';
part 'product_analytic_loader_bloc.freezed.dart';

@injectable
class ProductAnalyticLoaderBloc
    extends Bloc<ProductAnalyticLoaderEvent, ProductAnalyticLoaderState> {
  final IAnalyticRepository _analyticRepository;
  ProductAnalyticLoaderBloc(this._analyticRepository)
    : super(ProductAnalyticLoaderState.initial()) {
    on<ProductAnalyticLoaderEvent>(_onProductAnalyticLoaderEvent);
  }

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

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

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