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 '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 _repository;
  InventoryAnalyticLoaderBloc(this._repository)
    : super(InventoryAnalyticLoaderState.initial()) {
    on<InventoryAnalyticLoaderEvent>(_onInventoryAnalyticLoaderEvent);
  }

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

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

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

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