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 'dashboard_analytic_loader_event.dart';
part 'dashboard_analytic_loader_state.dart';
part 'dashboard_analytic_loader_bloc.freezed.dart';

@injectable
class DashboardAnalyticLoaderBloc
    extends Bloc<DashboardAnalyticLoaderEvent, DashboardAnalyticLoaderState> {
  final IAnalyticRepository _analyticRepository;

  DashboardAnalyticLoaderBloc(this._analyticRepository)
    : super(DashboardAnalyticLoaderState.initial()) {
    on<DashboardAnalyticLoaderEvent>(_onDashboardAnalyticLoader);
  }

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

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

        await result.fold(
          (failure) async {
            emit(
              state.copyWith(
                isFetching: false,
                failureOption: optionOf(failure),
              ),
            );
          },
          (dashboard) async {
            emit(
              state.copyWith(isFetching: false, dashboardAnalytic: dashboard),
            );
          },
        );
      },
    );
  }
}
