//
//  VeyetalsView.swift
//  LiveStreamExample
//
//  Created by Farooq Zaman on 24/11/2022.
//

import UIKit
import VeyetalsSDK

@objc (VeyetalsViewManager)
class VeyetalsViewManager: RCTViewManager {
 
  override static func requiresMainQueueSetup() -> Bool {
    return true
  }
 
  override func view() -> UIView! {
    return VeyetalsView()
  }
}


class VeyetalsView: UIView {
  
  @objc var onComplete: RCTBubblingEventBlock?
  @objc var onCancel: RCTBubblingEventBlock?
  weak var veyetalsViewController: UIViewController?
  
  @objc
  var config: NSDictionary = [:] {
    didSet {
      setNeedsLayout()
    }
  }
  
  var userId: String? {
    return config["userId"] as? String
  }
  
  var channelId: String? {
    return config["channelId"] as? String
  }
  
  var mode: VeyetalsMode? {
    return (config["mode"] as? String)?.caseInsensitiveCompare("finger") == .orderedSame ? .finger : .face
  }
  
  var isLightWeight: Bool{
    return (config["isLightWeight"] as? Bool) ?? false
  }

    var showUI: Bool{
    return (config["showUI"] as? Bool) ?? true
  }
  
  var customLabels: [String:String?]{
    return (config["customLabels"] as? [String:String?]) ?? [:]
  }
  
  override init(frame: CGRect) {
    super.init(frame: frame)
  }
    
  required init?(coder aDecoder: NSCoder) { fatalError("nope") }
  
  override func layoutSubviews() {
    super.layoutSubviews()
    
    if veyetalsViewController == nil {
      embed()
    } else {
      veyetalsViewController?.view.frame = bounds
    }
  }
    
    override func removeFromSuperview() {
        if let vc = veyetalsViewController{
            vc.willMove(toParent: nil)
            vc.view.removeFromSuperview()
            vc.removeFromParent()
            veyetalsViewController = nil
        }
        super.removeFromSuperview()
    }
  
  private func embed() {
    guard let parentVC = parentViewController else {
      return
    }
    
    let customLabels = CustomLabels(
            userMovementMessage: customLabels["userMovementErrorMessage"] ?? nil,
            faceAlignmentMessage: customLabels["faceAlignmentMessage"] ?? nil,
            inValidVitalAlertTitle:customLabels["INVALID_VITAL_ALERT_TITLE"] ?? nil,
            invalidRPPGHRAlertMsg: customLabels["INVALID_RPPG_HR_ALERT_MSG"] ?? nil,
            invalidRPPGHRVAlertMsg: customLabels["INVALID_RPPG_HRV_ALERT_MSG"] ?? nil,
            invalidRPPGStressAlrtMsg: customLabels["INVALID_RPPG_STRESS_ALERT_MSG"] ?? nil,
            invalidRPPGRRAlrtMsg: customLabels["INVALID_RPPG_RL_ALERT_MSG"] ?? nil,
            invalidRPPGBPAlrtMsg: customLabels["INVALID_RPPG_BP_ALERT_MSG"] ?? nil,
            invalidRPPGO2AlrtMsg: customLabels["INVALID_RPPG_O2_ALERT_MSG"] ?? nil,
            invalidPPGHRAlertMsg: customLabels["INVALID_PPG_HR_ALERT_MSG"] ?? nil,
            invalidPPGHRVAlertMsg:customLabels["INVALID_PPG_HRV_ALERT_MSG"] ?? nil,
            invalidPPGStressAlrtMsg: customLabels["INVALID_PPG_STRESS_ALERT_MSG"] ?? nil,
            invalidPPGRRAlrtMsg: customLabels["INVALID_PPG_RL_ALERT_MSG"] ?? nil,
            invalidPPGBPAlrtMsg: customLabels["INVALID_PPG_BP_ALERT_MSG"] ?? nil,
            invalidPPGO2AlrtMsg: customLabels["INVALID_PPG_O2_ALERT_MSG"] ?? nil
        )

    let storyboard = UIStoryboard(name: "Veyetals",
                                  bundle: Bundle(identifier: "com.markitech.VeyetalsSDK"))
    
    if (mode == .face){
      if let vc = storyboard.instantiateViewController(withIdentifier: "VeyetalsViewController") as? VeyetalsViewController{
        vc.userId = userId
        vc.channelId = channelId
        vc.veyetalsMode = mode ?? .face
        vc.isLightWeight = isLightWeight
        vc.showUI = showUI
        vc.customLabels = customLabels
        vc.deletegate = self
        vc.viewModel = VeyetalsViewModel()
        parentVC.addChild(vc)
        addSubview(vc.view)
        vc.view.frame = bounds
        vc.didMove(toParent: parentVC)
        self.veyetalsViewController = vc
      }
    }else if(mode == .finger){
        if let vc = storyboard.instantiateViewController(withIdentifier: "PPGScanViewController") as? PPGScanViewController{
          vc.userId = userId
          vc.channelId = channelId
          vc.veyetalsMode = mode ?? .face
          vc.isLightWeight = isLightWeight
          vc.showUI = showUI
          vc.customLabels = customLabels
          vc.deletegate = self
          parentVC.addChild(vc)
          addSubview(vc.view)
          vc.view.frame = bounds
          vc.didMove(toParent: parentVC)
          self.veyetalsViewController = vc
        }
    }
  }
}


extension VeyetalsView: VeyetalsScannerDelegate{
    func didCompleteScanning(results: [VeyetalResult]) {
        if let result = results.first(where: {$0.isFinal}){
            let vitals = ["Heart-rate": "\(result.heartRate)",
                          "HRV": "\(result.heartRateVariability)",
                          "02-saturation": "\(result.oxygenSaturation)",
                          "Respiration-rate": "\(result.respiratoryRate)",
                          "Systolic": "\(result.systolic)",
                          "Diastolic": "\(result.diastolic)",
                          "Stress-levels": "\(result.stressLevel)",
                          "snr": "\(result.snr)",
                          "glucose": "\(result.glucose)",
                          "emotion":"\(result.emotion)",
                          "isValidHeartRate": "\(result.isValidHeartRate)",
                          "isValidBloodPressure": "\(result.isValidBloodPressure)"]
            onComplete?(vitals)
        }else{
            onCancel?([:])
        }
    }
    
    func didCancelScanning() {
        onCancel?([:])
    }
}

extension UIView {
    var parentViewController: UIViewController? {
        var parentResponder: UIResponder? = self
        while parentResponder != nil {
            parentResponder = parentResponder!.next
            if let viewController = parentResponder as? UIViewController {
                return viewController
            }
        }
        return nil
    }
}
