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 'home_event.dart';
part 'home_state.dart';
part 'home_bloc.freezed.dart';

@injectable
class HomeBloc extends Bloc<HomeEvent, HomeState> {
  final IAnalyticRepository _analyticRepository;
  HomeBloc(this._analyticRepository) : super(HomeState.initial()) {
    on<HomeEvent>(_onHomeEvent);
  }
  Future<void> _onHomeEvent(HomeEvent event, Emitter<HomeState> emit) {
    return event.map(
      fetchedDashboard: (e) async {
        emit(state.copyWith(isFetching: true, failureOptionDashboard: none()));

        final result = await _analyticRepository.getDashboard(
          dateFrom: DateTime.now(),
          dateTo: DateTime.now(),
        );

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

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