//
//  CardTerminalToMonitor.swift
//  ABCBluetoothDemo
//
//  Created by AB Circle on 23/4/2021.
//  Copyright © 2020-2024 AB Circle. All rights reserved.
//

import Foundation
import ABCSmartCardIO

/// Class holding information on a monitored CardTerminal
class CardTerminalToMonitor {
    /// Reference to a CardTerminal being monitored
    private var terminal: CardTerminal?
    /// Name of CardTerminal being monitored
    private var terminalName : String = ""
    /// Flag indicating if the battery threshold noticed has been given already or not
    private var noticeGiven  : Bool   = false
    /// Battery threshold value to monitor for
    private var threshold    : UInt8  = 0
    
    /// Initialiser. Initialises the CardTerminal to monitor and the battery threshold.
    ///
    /// - Parameters:
    ///   - cardTerminal: CardTerminal to monitor
    ///   - batteryThreshold: Battery threshold value to monitor
    init (cardTerminal: CardTerminal, batteryThreshold: UInt8)
    {
        terminal     = cardTerminal
        terminalName = cardTerminal.getName()
        threshold    = batteryThreshold
        noticeGiven  = false
    }
    
    /// De-initialiser. cleans up
    deinit {
        cleanup()
    }
    
    /// Returns the CardTerminal name
    var cardTerminalName: String {
        return terminalName
    }
    
    /// Gets or sets the monitored battery threshold value
    var batteryThreshold: UInt8 {
        get {
            return threshold
        }
        set(threshold) {
            self.threshold = threshold
        }
    }
    
    /// Gets or sets the flag if a battery threshold notice has been given or not
    var batteryNoticeGiven: Bool {
        get {
            return noticeGiven
        }
        set (noticeGiven) {
            self.noticeGiven = noticeGiven
        }
    }
    
    /// Checks if the battery level of the monitored CardTeminal has reached the set battery threshold.
    ///
    /// - Returns: True if threshold has been reached, else false
    func batteryThresholdReached() -> Bool {
        var reached: Bool = false
        
        if !batteryNoticeGiven {
            var level: UInt8 = 0xFF
            
            if let currentLevel = try? terminal?.getBatteryLevel() {
                level = currentLevel
            }
            print("Terminal ", terminalName, " level = ", level, ", threshold = ", threshold)
            reached = (level <= threshold)
        }
        return reached
    }
    
    /// Cleans up the CardTerminal reference
    func cleanup() {
        terminal = nil
    }
}
