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 'bluetooth_connect_event.dart';
part 'bluetooth_connect_state.dart';
part 'bluetooth_connect_bloc.freezed.dart';

@injectable
class BluetoothConnectBloc
    extends Bloc<BluetoothConnectEvent, BluetoothConnectState> {
  final IPrinterRepository _printerRepository;
  BluetoothConnectBloc(this._printerRepository)
    : super(BluetoothConnectState.initial()) {
    on<BluetoothConnectEvent>(_onBluetoothConnectEvent);
  }

  Future<void> _onBluetoothConnectEvent(
    BluetoothConnectEvent event,
    Emitter<BluetoothConnectState> emit,
  ) {
    return event.map(
      connect: (e) async {
        emit(state.copyWith(isConnecting: true, failureOrSuccee: none()));

        final result = await _printerRepository.connectBluetooth(e.macAddress);

        result.fold(
          (failure) => emit(state.copyWith(isConnecting: false)),
          (success) => emit(state.copyWith(isConnecting: false)),
        );
      },
    );
  }
}
