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 'inventory_analytic_loader_event.dart';
part 'inventory_analytic_loader_state.dart';
part 'inventory_analytic_loader_bloc.freezed.dart';

@injectable
class InventoryAnalyticLoaderBloc
    extends Bloc<InventoryAnalyticLoaderEvent, InventoryAnalyticLoaderState> {
  final IAnalyticRepository _analyticRepository;
  InventoryAnalyticLoaderBloc(this._analyticRepository)
    : super(InventoryAnalyticLoaderState.initial()) {
    on<InventoryAnalyticLoaderEvent>(_onInventoryAnalyticLoaderEvent);
  }

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

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

        emit(
          result.fold(
            (l) => state.copyWith(isFetching: false, failureOption: some(l)),
            (r) => state.copyWith(
              isFetching: false,
              failureOption: none(),
              inventoryAnalytic: r,
            ),
          ),
        );
      },
    );
  }
}
