import 'package:bloc/bloc.dart';
import 'package:dartz/dartz.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:injectable/injectable.dart';

import '../../../domain/printer/printer.dart';

part 'printer_loader_event.dart';
part 'printer_loader_state.dart';
part 'printer_loader_bloc.freezed.dart';

@injectable
class PrinterLoaderBloc extends Bloc<PrinterLoaderEvent, PrinterLoaderState> {
  final IPrinterRepository _printerRepository;
  PrinterLoaderBloc(this._printerRepository)
    : super(PrinterLoaderState.initial()) {
    on<PrinterLoaderEvent>(_onPrinterLoaderEvent);
  }

  Future<void> _onPrinterLoaderEvent(
    PrinterLoaderEvent event,
    Emitter<PrinterLoaderState> emit,
  ) {
    return event.map(
      getByCode: (e) async {
        emit(state.copyWith(isFetching: true, failureOption: none()));

        final result = await _printerRepository.getPrinterByCode(e.code);

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