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';
import '../../../domain/analytic/repositories/i_analytic_repository.dart';

part 'purchasing_analytic_loader_event.dart';
part 'purchasing_analytic_loader_state.dart';
part 'purchasing_analytic_loader_bloc.freezed.dart';

@injectable
class PurchasingAnalyticLoaderBloc
    extends Bloc<PurchasingAnalyticLoaderEvent, PurchasingAnalyticLoaderState> {
  final IAnalyticRepository _analyticRepository;

  PurchasingAnalyticLoaderBloc(this._analyticRepository)
      : super(PurchasingAnalyticLoaderState.initial()) {
    on<PurchasingAnalyticLoaderEvent>(_onEvent);
  }

  Future<void> _onEvent(
    PurchasingAnalyticLoaderEvent event,
    Emitter<PurchasingAnalyticLoaderState> emit,
  ) {
    return event.map(
      rangeDateChanged: (e) async {
        emit(state.copyWith(dateFrom: e.dateFrom, dateTo: e.dateTo));
      },
      outletChanged: (e) async {
        emit(state.copyWith(outletId: e.outletId));
      },
      fetched: (e) async {
        emit(state.copyWith(
          isFetching: true,
          failureOptionPurchasing: none(),
        ));

        final result = await _analyticRepository.getPurchasing(
          dateFrom: state.dateFrom,
          dateTo: state.dateTo,
          outletId: state.outletId,
          groupBy: state.groupBy,
        );

        final newState = result.fold(
          (f) => state.copyWith(failureOptionPurchasing: optionOf(f)),
          (purchasing) => state.copyWith(purchasing: purchasing),
        );

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