//
//  AppController.swift
//  cmbSDKToolkitSample
//
//

import Foundation
import Combine
import cmbSDK

class AppController {
    
    var appState: AppState
    var readerManager = ReaderManager()
    private var subscriptions = [AnyCancellable]()
    
    init() {
        self.appState = AppState(readerState: self.readerManager.readerState)
        subscribeToChanges()
    }
    
    func subscribeToChanges() {
        self.subscriptions.append(self.appState.$pairedDeviceIsAvailable.sink { pairedDeviceIsAvailable in
            if pairedDeviceIsAvailable {
                self.readerManager.connect(peripheralUUID: self.appState.settings.pairedDeviceUUID!)
            }
        })
        self.subscriptions.append(self.readerManager.readerState.$connectionState.sink { connectionState in
            if connectionState == CMBConnectionStateDisconnected {
                self.appState.pairedDeviceIsAvailable = false
            }
        })
    }
}
