//
//  BTPairingView.swift
//  cmbSDKToolkitSample
//
//

import SwiftUI
import cmbSDKToolkit

struct BTPairingView: UIViewControllerRepresentable {
    
    @EnvironmentObject var appState: AppState
    
    func makeUIViewController(context: Context) -> UIViewController {
        let settingsStoryBoard = UIStoryboard(name: "cmbSDKToolkit", bundle: Bundle(identifier: "com.cognex.cmbSDKToolkit"))
        let btPairingVC = settingsStoryBoard.instantiateViewController(withIdentifier: "BT_AUTO_CONNECT_VC") as! BTAutoConnect
        btPairingVC.peripheralUUID = appState.settings.pairedDeviceUUID
        let navController = UINavigationController(rootViewController: btPairingVC as! UIViewController)
        navController.navigationBar.topItem?.hidesBackButton = true
        
        return navController
    }

    func updateUIViewController(_ uiViewController: UIViewController, context: Context) {
        //nothing to do
    }
    
    func makeCoordinator() -> Coordinator {
        Coordinator(btPairingView: self)
    }
}

class Coordinator: NSObject {

    private var btPairingView: BTPairingView

    init(btPairingView: BTPairingView) {
        self.btPairingView = btPairingView
        super.init()
        NotificationCenter.default.addObserver(self, selector: #selector(handlePeripheralDidPairNotification(_ :)), name: .cognexBTDeviceDidPairNotification, object: nil)
    }

    @objc func handlePeripheralDidPairNotification(_ notification: NSNotification) {
        let peripheralUUID = notification.userInfo![pairedCognexBTDeviceUUIDKey] as! UUID
        btPairingView.appState.settings.pairedDeviceUUID = peripheralUUID
        btPairingView.appState.pairedDeviceIsAvailable = true
    }
}
