//
//  Status.swift
//  SiiLibSample
//

import Foundation

class Status: NSObject, ObservableObject, SIIPrinterManagerDelegate {
    @Published var printerStatusStr: String
    @Published var barcodeStatus: String
    @Published var isBarcodeOnline: Bool
    @Published var barcodeData: String
    @Published var isBarcodeEncode: Bool
    
    override init() {
        self.printerStatusStr = ""
        self.barcodeStatus = ""
        self.isBarcodeOnline = false
        self.barcodeData = ""
        self.isBarcodeEncode = true
    }
    
    /// Implementation delegate function defined in SIIPrinterManagerDelegate
    func didStatusChange(_ printerManager: SIIPrinterManager!, status: Int) {
        DispatchQueue.main.async {
        self.printerStatusStr = String(format: "0x%02X", status)
        }
    }
    
    /// Implementation delegate function defined in SIIPrinterManagerDelegate
    func didBarcodeScannerReadData(_ printerManager: SIIPrinterManager!, data: Data) {
        DispatchQueue.main.async {
            if self.isBarcodeEncode {
                let encodedStringOptional: String? = String(data: data, encoding: .shiftJIS)
                if let encodedStringBinded = encodedStringOptional {
                    self.barcodeData = encodedStringBinded
                } else {
                    self.barcodeData = "Encoding failed!!"
                }
            } else {
                let endCount = data.count - 1
                let binaryString = data[0...endCount].map { String(format: "%01X", $0) }.joined()
                self.barcodeData = binaryString
            }
        }
    }
    
    /// Implementation delegate function defined in SIIPrinterManagerDelegate
    func didBarcodeScannerChangedOnline(_ printerManager: SIIPrinterManager!) {
        DispatchQueue.main.async {
            self.barcodeStatus = "Online"
            self.isBarcodeOnline = true
        }
    }
    
    /// Implementation delegate function defined in SIIPrinterManagerDelegate
    func didBarcodeScannerChangedOffline(_ printerManager: SIIPrinterManager!) {
        DispatchQueue.main.async {
            self.barcodeStatus = "Offline"
            self.isBarcodeOnline = false
        }
    }
    
    func resetStatus() {
        DispatchQueue.main.async {
            self.printerStatusStr = ""
            self.barcodeStatus = ""
            self.barcodeData = ""
        }
    }
}
