import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:mobile_scanner/mobile_scanner.dart';

enum QRStatus { initial, scanning, scanned, error }

class QRState {
  final String? qrData;
  final QRStatus status;

  QRState({this.qrData, required this.status});

  factory QRState.initial() => QRState(status: QRStatus.initial);
  factory QRState.scanning() => QRState(status: QRStatus.scanning);
  factory QRState.scanned(String qrData) => QRState(status: QRStatus.scanned, qrData: qrData);
  factory QRState.error() => QRState(status: QRStatus.error);
}

class QRBloc extends Cubit<QRState> {
  QRBloc() : super(QRState.initial());

  void startScanning() {
    emit(QRState.scanning());
  }

  void scanQRCode(String qrData) {
    emit(QRState.scanned(qrData));
  }

  void setError() {
    emit(QRState.error());
  }

  void reset() {
    emit(QRState.initial());
  }
}

abstract class QrScannerV2Event {}

class ToggleTorchEvent extends QrScannerV2Event {}

class SwitchCameraEvent extends QrScannerV2Event {}

class QrScannerV2State {
  final bool torchOn;
  final CameraFacing currentCamera;

  QrScannerV2State({required this.torchOn, required this.currentCamera});

  QrScannerV2State copyWith({bool? torchOn, CameraFacing? currentCamera}) {
    return QrScannerV2State(
      torchOn: torchOn ?? this.torchOn,
      currentCamera: currentCamera ?? this.currentCamera,
    );
  }
}

class QrScannerV2Bloc extends Bloc<QrScannerV2Event, QrScannerV2State> {
  QrScannerV2Bloc() : super(QrScannerV2State(torchOn: false, currentCamera: CameraFacing.back));

  @override
  Stream<QrScannerV2State> mapEventToState(QrScannerV2Event event) async* {
    if (event is ToggleTorchEvent) {
      yield state.copyWith(torchOn: !state.torchOn);
    } else if (event is SwitchCameraEvent) {
      yield state.copyWith(currentCamera: state.currentCamera == CameraFacing.front ? CameraFacing.back : CameraFacing.front);
    }
  }
}