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 '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 _repository;
  DashboardAnalyticLoaderBloc(this._repository)
    : super(DashboardAnalyticLoaderState.initial()) {
    on<DashboardAnalyticLoaderEvent>(_onDashboardAnalyticLoaderEvent);
  }

  Future<void> _onDashboardAnalyticLoaderEvent(
    DashboardAnalyticLoaderEvent event,
    Emitter<DashboardAnalyticLoaderState> emit,
  ) {
    return event.map(
      rangeDateChanged: (e) async {
        emit(state.copyWith(dateFrom: e.dateFrom, dateTo: e.dateTo));
      },
      fetched: (e) async {
        emit(
          state.copyWith(
            isFetching: true,
            failureOptionDashboardAnalytic: none(),
          ),
        );

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

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

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