//
//  ScanbotSDKCapacitorPlugin.swift
//  Plugin
//
//  Copyright © 2024 Scanbot SDK GmbH. All rights reserved.
//

import Capacitor
import ScanbotSDKNativeWrapper

extension ScanbotSDKCapacitorPlugin {
  
  @objc func scanBarcodesFromImage(_ call: CAPPluginCall) {
    SBBarcode.scanFromImage(options: call.data, resultDelegate: call.delegate)
  }
  
  @objc func scanBarcodesFromPdf(_ call: CAPPluginCall) {
    SBBarcode.scanFromPDF(options: call.data, resultDelegate: call.delegate)
  }
  
  @objc func parseBarcodeDocument(_ call: CAPPluginCall) {
    SBBarcode.parseDocument(options: call.data, resultDelegate: call.delegate)
  }
  
  @objc func startBarcodeScanner(_ call: CAPPluginCall) {
    guard let parentVC = presentViewControllerOrReject(call) else {
      return
    }
    
    if self.barcodeItemMapperPluginCall != nil {
      
      if let safeBarcodeItemMapperPluginCall = self.barcodeItemMapperPluginCall {
        self.bridge?.releaseCall(safeBarcodeItemMapperPluginCall)
        self.barcodeItemMapperPluginCall = nil
      }
      
      SBBarcode.startScanner(
        parentViewController: parentVC,
        configuration: call.data,
        resultDelegate: call.delegate) { barcodeItem in
          if let safeBarcodeItemMapperPluginCall = self.barcodeItemMapperPluginCall {
            safeBarcodeItemMapperPluginCall.resolve(barcodeItem)
          }
        }
    } else {
      SBBarcode.startScanner(
        parentViewController: parentVC,
        configuration: call.data,
        resultDelegate: call.delegate
      )
    }
    
  }
  
  // MARK: public helper methods that are used only by us from the plugin middle layer (not exposed to the users)
  @objc func registerBarcodeItemMapperCallback(_ call: CAPPluginCall) {
    call.keepAlive = true
    barcodeItemMapperPluginCall = call
  }
  
  @objc func onBarcodeItemMapper(_ call: CAPPluginCall) {
    guard let barcodeUUID = call.options["barcodeItemUuid"] as? String else {
      call.reject(self.missingRequiredPropertyErrorMsg + "barcodeItemUuid")
      return
    }
    
    let barcodeMappedData = call.options["barcodeMappedData"] as? [String: Any]
    
    SBBarcode.onBarcodeItemMapper(barcodeItemUUID: barcodeUUID, barcodeMappedDataAsDictionary: barcodeMappedData)
  }
}
