import Cocoa

class DeviceIdTableViewController: NSViewController {
    private var deviceIdList:Array<NSNumber> = []

    @IBOutlet weak var spinner: NSProgressIndicator!
    @IBOutlet weak var tableView: NSTableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.tableView.target = self
        self.tableView.doubleAction = #selector(tableViewDoubleAction)
    }
    
    override func viewDidAppear() {
        super.viewDidAppear()
        DispatchQueue.global(qos: .default).async { [weak self] in
            guard let strongSelf = self else { return }
            strongSelf.setIsHiddenSpinner(isHidden: false)
        }
        let config = MPosControllerConfig()
        let ad = NSApplication.shared.delegate as! AppDelegate
        config.selectInterface(MPOS_INTERFACE_TYPE(rawValue: ad.conntectionType)!, address: ad.connectionString)
        if config.openService() == .RES_SUCCESS {
            deviceIdList = config.searchDevices()
        }
        config.closeService(0)
        tableView.reloadData()
        setIsHiddenSpinner(isHidden: true)
    }
    
    func setIsHiddenSpinner(isHidden:Bool) {
        DispatchQueue.main.async { [weak self] in
            guard let strongSelf = self else { return }
            strongSelf.spinner.isHidden = isHidden
            if isHidden {
                strongSelf.spinner.stopAnimation(nil)
            } else {
                strongSelf.spinner.startAnimation(nil)
            }
        }
    }
    
    @IBAction func onClose(_ sender: Any) {
        tableViewDoubleAction(sender)
    }
    
    @objc func tableViewDoubleAction(_ sender: Any) {
        self.dismiss(self)
    }
}

extension DeviceIdTableViewController: NSTableViewDataSource {
    func numberOfRows(in tableView: NSTableView) -> Int {
        return deviceIdList.count
    }
}

extension DeviceIdTableViewController: NSTableViewDelegate {
    func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
        var identifier = ""
        var text = ""
        let deviceId = deviceIdList[row]
        
        if tableColumn == tableView.tableColumns[0] {
            identifier = "DeviceId"
            text = "\(deviceId)"
        } else if tableColumn == tableView.tableColumns[1] {
            identifier = "Category"
            let value = deviceId.intValue
            if(value > 0 && value < 10)             { text = "Label Printer"}
            else if(value == 10)                    { text = "POS Printer (internal)"}
            else if(value > 10 && value < 20)       { text = "POS Printer"}
            else if(value >= 20 && value < 30)      { text = "HID"}
            else if(value >= 30 && value < 40)      { text = "MSR"}
            else if(value >= 40 && value < 50)      { text = "Scanner"}
            else if(value >= 60 && value < 69)      { text = "RFID"}
            else if(value >= 70 && value < 79)      { text = "DALLAS KEY"}
            else if(value >= 80 && value < 89)      { text = "NFC"}
            else if(value >= 100 && value < 110)    { text = "Unregistered USB UART Device"}
            else if(value >= 110 && value < 120)    { text = "Customer Display"}
            else if(value >= 120 && value < 130)    { text = "TTY USB (USB to Serial)"}
            else if(value >= 130 && value < 140)    { text = "SCALE"}
            else{
                text = "Unknown Type Device";
            }
        }
        
        guard let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(identifier), owner: nil) as? NSTableCellView else { return nil }
        cell.textField?.stringValue = text
        
        return cell
    }
    
    func tableViewSelectionDidChange(_ notification: Notification) {
        guard let tbl = notification.object as? NSTableView else { return }
        
        if tbl.selectedRow > deviceIdList.count ||
           tbl.selectedRow < 0 {
            return
        }
        
        let ad = NSApplication.shared.delegate as! AppDelegate
        let deviceId = deviceIdList[tbl.selectedRow]
        
        ad.deviceId = deviceId.intValue
    }
}
