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 'sales_loader_event.dart';
part 'sales_loader_state.dart';
part 'sales_loader_bloc.freezed.dart';

@injectable
class SalesLoaderBloc extends Bloc<SalesLoaderEvent, SalesLoaderState> {
  final IAnalyticRepository _analyticRepository;
  SalesLoaderBloc(this._analyticRepository)
    : super(SalesLoaderState.initial()) {
    on<SalesLoaderEvent>(_onSalesLoaderEvent);
  }

  Future<void> _onSalesLoaderEvent(
    SalesLoaderEvent event,
    Emitter<SalesLoaderState> emit,
  ) {
    return event.map(
      rangeDateChanged: (e) async {
        emit(state.copyWith(dateFrom: e.dateFrom, dateTo: e.dateTo));
      },
      fectched: (e) async {
        emit(state.copyWith(isFetching: true, failureOptionSales: none()));

        final result = await _analyticRepository.getSales(
          dateFrom: state.dateFrom,
          dateTo: state.dateTo,
        );

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

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