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 '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 _repository;
  ProductAnalyticLoaderBloc(this._repository)
    : super(ProductAnalyticLoaderState.initial()) {
    on<ProductAnalyticLoaderEvent>(_onProductAnalyticLoaderEvent);
  }

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

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

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

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