//
//  ScanbotBarcodeSDKPluginResultDelegate.swift
//  CapacitorPluginScanbotBarcodeScannerSdk
//
//  Created by Marko Jakov on 08.04.24.
//

import Foundation
import Capacitor
import ScanbotBarcodeSDKWrapper

class ScanbotBarcodeSDKPluginResultDelegate: PluginResultDelegate {

    private let call: CAPPluginCall
    private let onPromiseHandled: (() -> Void)?
    
    init(_ call: CAPPluginCall, onPromiseHandled: (() -> Void)? = nil) {
        self.call = call
        self.onPromiseHandled = onPromiseHandled
    }
    
    func didResolvePromise(_ result: Any?) {
        
        if let boolResult = result as? Bool {
            call.resolve(["result": boolResult])
        } else if let stringResult = result as? String {
            call.resolve(["result": stringResult])
        } else if let stringArrayResult = result as? [String] {
            call.resolve(["result": stringArrayResult])
        } else if let dictionaryResult = result as? [String: Any] {
            call.resolve(dictionaryResult)
        } else {
            call.resolve()
        }
        
        onPromiseHandled?()
    }
  
  func didRejectPromise(_ error: SBErrorResponse) {
    call.reject(error.message, String(error.code))
    onPromiseHandled?()
  }
}
