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

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

part 'bluetooth_loader_event.dart';
part 'bluetooth_loader_state.dart';
part 'bluetooth_loader_bloc.freezed.dart';

@injectable
class BluetoothLoaderBloc
    extends Bloc<BluetoothLoaderEvent, BluetoothLoaderState> {
  final IPrinterRepository _printerRepository;
  BluetoothLoaderBloc(this._printerRepository)
    : super(BluetoothLoaderState.initial()) {
    on<BluetoothLoaderEvent>(_onBluetoothLoaderEvent);
  }

  Future<void> _onBluetoothLoaderEvent(
    BluetoothLoaderEvent event,
    Emitter<BluetoothLoaderState> emit,
  ) {
    return event.map(
      fetched: (e) async {
        emit(state.copyWith(isFetching: true, failureOption: none()));

        final result = await _printerRepository.getPairedBluetoothDevices();

        result.fold(
          (failure) => emit(
            state.copyWith(failureOption: optionOf(failure), isFetching: false),
          ),
          (devices) => emit(
            state.copyWith(
              bluetoothDevices: devices,
              failureOption: none(),
              isFetching: false,
            ),
          ),
        );
      },
    );
  }
}
