import Flutter
import UIKit
import VitalSignEngineCore

public class SwiftVitalSignCameraPlugin: NSObject, FlutterPlugin {
  public static func register(with registrar: FlutterPluginRegistrar) {
      
    let channel = FlutterMethodChannel(name: "vital_sign_camera_plugin", binaryMessenger: registrar.messenger())
    let instance = SwiftVitalSignCameraPlugin()
    registrar.addMethodCallDelegate(instance, channel: channel)
      
    registrar.register(VitalSignCameraFactory(messenger: registrar.messenger()), withId: "ai.panoptic/flutter_vital_sign_camera")
  }

  public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
      if call.method == "availableCameraDevices" {
          let devices = VitalSignCamera.availableCameraDevices()
          result(devices.map({ $0.flutterCompatibleDict }))
      }
      if call.method == "requestCameraPermission" {
          VitalSignCamera.requestCameraPermission().done { status in
              result(status.rawValue)
          }.catch { error in
              result(FlutterError(code: "\(error.code)", message: error.message, details: nil))
          }
      }
      if call.method == "getCameraPermissionStatus" {
          let status = VitalSignCamera.getCameraPermissionStatus()
          result(status.rawValue)
      }
  }
    
}

fileprivate extension CameraDevice {
    var flutterCompatibleDict:[String:Any] {
        [
            "id": id,
            "devices": devices.map { $0.rawValue },
            "position": position.rawValue,
            "name": name,
            "hasFlash": NSNumber(value: hasFlash),
            "hasTorch": NSNumber(value: hasTorch),
            "minZoom": NSNumber(value: Double(minZoom)),
            "neutralZoom": NSNumber(value: Double(neutralZoom)),
            "maxZoom": NSNumber(value: Double(maxZoom)),
            "isMultiCam": NSNumber(value: isMultiCam),
            "supportsParallelVideoProcessing": NSNumber(value: supportsParallelVideoProcessing),
            "supportsDepthCapture": NSNumber(value: supportsDepthCapture),
            "supportsRawCapture": NSNumber(value: supportsRawCapture),
            "supportsLowLightBoost": NSNumber(value: supportsLowLightBoost),
            "supportsFocus": NSNumber(value: supportsFocus),
            "formats": formats.map { format -> [String: Any] in
                format.flutterCompatibleDict
            },
        ]
    }
}

fileprivate extension CameraCaptureFormat {
    var flutterCompatibleDict:[String:Any] {
        var dict:[String:Any] = [
            "videoStabilizationModes": videoStabilizationModes.map { $0.rawValue },
            "autoFocusSystem": autoFocusSystem.rawValue,
            "photoHeight": NSNumber(value: Double(photoHeight)),
            "photoWidth": NSNumber(value: Double(photoWidth)),
            "videoHeight": NSNumber(value: Double(videoHeight)),
            "videoWidth": NSNumber(value: Double(videoWidth)),
            "maxISO": NSNumber(value: Int(maxISO)),
            "minISO": NSNumber(value: Int(minISO)),
            "fieldOfView": NSNumber(value: Double(fieldOfView)),
            "maxZoom": NSNumber(value: Double(maxZoom)),
            "colorSpaces": colorSpaces.map { $0.rawValue },
            "supportsVideoHDR": NSNumber(value: supportsVideoHDR),
            "supportsPhotoHDR": NSNumber(value: supportsPhotoHDR),
            "frameRateRanges": frameRateRanges.map {
              [
                "minFrameRate": NSNumber(value: Int($0.minFrameRate)),
                "maxFrameRate": NSNumber(value: Int($0.maxFrameRate)),
              ]
            },
            "pixelFormat": pixelFormat.rawValue,
        ]
        
        if let isHighestPhotoQualitySupported = isHighestPhotoQualitySupported {
            dict["isHighestPhotoQualitySupported"] = isHighestPhotoQualitySupported
        }
        
        return dict
    }
}
