import Combine
import NFCSDK

class NFCViewModel: ObservableObject, IOSNFCCallbacks {
    @Published var deviceId = ""
    @Published var deviceRssi = ""
    @Published var devicePassword = "123456"

    private lazy var nfcHelper = IOSNFCHelper(callback: self)

    func discovered(id: String, isNew: Bool, rssi: Int32) {
        DispatchQueue.main.async {
            self.deviceId = id
            self.deviceRssi = String(rssi)
        }
    }
    
    func finished() {
        DispatchQueue.main.async {
            self.deviceId = ""
            self.deviceRssi = ""
        }
    }
    
    func charging(res: String, level: Int32) {
        switch res {
        case "OK":
            print("Charging level: \(level)%")
        case "UNAUTHORIZED":
            print("Unauthorized")
        case "ERROR":
            print("Charging Failed")
        default:
            break
        }
    }
    
    func controlling(res: String, progress: Int32, ctrl: String) {
        switch res {
        case "OK":
            print("Controlling: \(ctrl), progress: \(progress)")
        case "UNAUTHORIZED":
            print("Unauthorized")
        case "ERROR":
            print("Control failed")
        default:
            break
        }
    }
    
    func setKey(res: String, password: String) {
        switch res {
        case "OK":
            print("Password set successfully")
        case "UNAUTHORIZED":
            print("Unauthorized")
        case "ERROR":
            print("Password setting failed")
        default:
            break
        }
    }
    
    func customData(res: String, config: CustomDataConfig, data: Data?) {
        switch res {
        case "OK":
            print("Operation successful: \(config.name)")
        case "ERROR":
            print("Operation failed: \(config.name)")
        default:
            break
        }
        if let data0 = data {
            print(data0.map { String(format: "%02X", $0) }.joined(separator: " "))
        }
    }
    
    func mLock() {
        nfcHelper.lock(password: devicePassword)
        nfcHelper.startScan()
    }
    
    func mUnlock() {
        nfcHelper.unlock(password: devicePassword)
        nfcHelper.startScan()
    }
    
    func mSetKey(sKey: String) {
        nfcHelper.setKey(password: devicePassword, sKey: sKey)
        nfcHelper.startScan()
    }
    
    func mWriteCustomData(data: Data) {
        nfcHelper.customDataOperation(config: .write, customData: data)
        nfcHelper.startScan()
    }
    
    func mReadCustomData() {
        nfcHelper.customDataOperation(config: .read, customData: nil)
        nfcHelper.startScan()
    }
}
