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

import Capacitor
import Foundation
import ScanbotSDKNativeWrapper

public class ResultDelegate: PluginResultDelegate {
  
  private let call: CAPPluginCall
  private let onPromiseHandled: (() -> Void)?
  
  init(_ call: CAPPluginCall, onPromiseHandled: (() -> Void)? = nil) {
    self.call = call
    self.onPromiseHandled = onPromiseHandled
  }
  
  public 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?()
  }
  
  public func didRejectPromise(_ error: ScanbotSDKNativeWrapper.SBErrorResponse) {
    call.reject(error.message, String(error.code))
    onPromiseHandled?()
  }

}
