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/outlet/outlet.dart';

part 'current_outlet_loader_event.dart';
part 'current_outlet_loader_state.dart';
part 'current_outlet_loader_bloc.freezed.dart';

@injectable
class CurrentOutletLoaderBloc
    extends Bloc<CurrentOutletLoaderEvent, CurrentOutletLoaderState> {
  final IOutletRepository _repository;
  CurrentOutletLoaderBloc(this._repository)
    : super(CurrentOutletLoaderState.initial()) {
    on<CurrentOutletLoaderEvent>(_onCurrentOutletLoaderEvent);
  }

  Future<void> _onCurrentOutletLoaderEvent(
    CurrentOutletLoaderEvent event,
    Emitter<CurrentOutletLoaderState> emit,
  ) {
    return event.map(
      fetched: (e) async {
        emit(state.copyWith(isFetching: true, failureOptionOutlet: none()));

        final result = await _repository.currentOutlet();

        var data = result.fold(
          (f) => state.copyWith(failureOptionOutlet: optionOf(f)),
          (currentOutlet) => state.copyWith(outlet: currentOutlet),
        );

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