//
//  SiiPrinterModel.swift
//  SiiLibSample
//

import Foundation
import SwiftUI

class SiiPrinterModel : ObservableObject {
    @AppStorage(KEY_PRINTER_ADDRESS) var address = VALUE_PRINTER_ADDRESS
    @AppStorage(KEY_PRINTER_PORT_TYPE) var portType = VALUE_PRINTER_PORT_TYPE
    @AppStorage(KEY_PRINTER_MODELNAME) var modelName = VALUE_PRINTER_MODELNAME
    @AppStorage(KEY_TEXTFIELD_ADDRESS) var addressStr = VALUE_TEXTFIELD_ADDRESS
    
    @Published var printer: SiiPrinter
    @Published var isShowLoadingView: Bool = false
    @Published var isShowAlert: Bool = false
    @Published var alertStr: String = ""
    @Published var isShowPrinterListLoadingView: Bool = false
    
    init() {
        self.printer = SiiPrinter()
        self.printer = initWithPrinterInformation(address: self.address, modelName: self.modelName, portType: self.portType)
    }
    
    func setAppStorage(printer: SiiPrinter) {
        self.address = printer.address
        self.portType = printer.portType
        self.modelName = printer.modelName
        self.addressStr = returnAddressStr()
    }
    
    func getPrinter(printer: SiiPrinter) {
        self.printer = printer
    }
    
    /// Set a printer instance from given address, modelName and portType
    func initWithPrinterInformation(address: String, modelName: String, portType: String) -> SiiPrinter {
        var printer = SiiPrinter()
        printer.address = address
        printer.modelName = modelName
        printer.portType = portType
        printer.model = printer.getPrinterModel(modelName: modelName)
        printer.type = printer.getPrinterType(portType: portType)
        return printer
    }
    
    func returnAddressStr() -> String {
        if self.address != "" && self.portType != "" {
            return self.address + "(" + self.portType + ")"
        } else {
            return ""
        }
    }
    
    func showLoadingView(_ show: Bool) {
        DispatchQueue.main.async {
            self.isShowLoadingView = show
        }
    }
    
    func setAlert(_ str: String) {
        DispatchQueue.main.async {
            self.alertStr = str
            self.isShowAlert = (str != "")
        }
    }
    
    func showPrinterListLoadingView(_ show: Bool) {
        DispatchQueue.main.async {
            self.isShowPrinterListLoadingView = show
        }
    }
    
}
