import UIKit

class DevListTableViewController: UITableViewController {
    private let resuseIdentifier = "deviceListCell"
    private let sections:[String] = ["Bluetooth classic", "Network", "BLE", "USB"]
    // Array
    private var btDevices : Array<MPosDeviceInfo> = []
    private var networkDevices : Array<MPosDeviceInfo> = []
    private var bleDevices : Array<MPosDeviceInfo> = []
    private var usbDevices : Array<MPosDeviceInfo> = []
    // Spinner
    private var spinner : UIActivityIndicatorView?

    override func viewDidLoad() {
        super.viewDidLoad()
        btDevices = []
        networkDevices = []
        bleDevices = []
        usbDevices = []
        self.tableView.tableFooterView = UIView()
        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: resuseIdentifier)
    }

    override func viewDidAppear(_ animated: Bool) {
        self.showSpinnerAtFooter()
        DispatchQueue.global(qos: .background).async { [weak self] in
            guard let strongSelf = self else { return }
            let lookup = MPosLookup()
            strongSelf.btDevices = lookup.getBluetoothDevices()
//            strongSelf.networkDevices = lookup.getNetworkDevices()
            strongSelf.networkDevices = UDPSetting.getNetworkInfos()
            strongSelf.bleDevices = lookup.getBLEDevices()
            strongSelf.usbDevices = lookup.getUSBDevices()
            DispatchQueue.main.async {
                strongSelf.tableView.reloadData()
                strongSelf.hideSpinnerAtFooter()
            }
        }
    }
    // MARK: - Table view data source
    override func numberOfSections(in tableView: UITableView) -> Int {
        return sections.count
    }

    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return sections[section];
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        var numberofRow: Int? = 0;
        switch section {
        case 0: numberofRow = self.btDevices.count
        case 1: numberofRow = self.networkDevices.count
        case 2: numberofRow = self.bleDevices.count
        case 3: numberofRow = self.usbDevices.count
        default:
            return 0
        }
        return numberofRow!
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: resuseIdentifier, for: indexPath)
        cell = UITableViewCell(style: .subtitle, reuseIdentifier: resuseIdentifier)
        if indexPath.section == 0 /* Bluetooth */{
            if self.btDevices.count > 0{
                cell.textLabel?.text = self.btDevices[indexPath.row].name
                cell.detailTextLabel?.text = " \(self.btDevices[indexPath.row].serialNumber!)"
            }
        }else if indexPath.section == 1 /* Network */{
            if self.networkDevices.count > 0{
                cell.textLabel?.text = self.networkDevices[indexPath.row].name.count > 0 ? self.networkDevices[indexPath.row].name : "Network Device"
                cell.detailTextLabel?.text = " \(self.networkDevices[indexPath.row].address!):\(self.networkDevices[indexPath.row].portNumber!)"
            }
        }else if indexPath.section == 2 /* BLE */{
            if self.bleDevices.count > 0{
                cell.textLabel?.text = self.bleDevices[indexPath.row].name.count > 0 ? self.bleDevices[indexPath.row].name : "BLE Device"
                cell.detailTextLabel?.text = " \(self.bleDevices[indexPath.row].macAddress!)"
            }
        }else if indexPath.section == 3 /* USB */{
            if self.usbDevices.count > 0{
                cell.textLabel?.text = self.usbDevices[indexPath.row].name
                cell.detailTextLabel?.text = " \(self.usbDevices[indexPath.row].serialNumber!)"
            }
        }
        return cell
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let ad = UIApplication.shared.delegate as? AppDelegate
        ad?.networkDevice = nil
        if indexPath.section == 0 /* Bluetooth */{
            ad?.deviceName = self.btDevices[indexPath.row].name
            ad?.conntectionType = self.btDevices[indexPath.row].interfaceType.rawValue
            ad?.connectionString = self.btDevices[indexPath.row].serialNumber
        }else if indexPath.section == 1 /* Network */ {
            ad?.deviceName = self.networkDevices[indexPath.row].name
            ad?.conntectionType = self.networkDevices[indexPath.row].interfaceType.rawValue
            ad?.connectionString = "\(self.networkDevices[indexPath.row].address!):\(self.networkDevices[indexPath.row].portNumber!)"
            ad?.networkDevice = self.networkDevices[indexPath.row]
        }else if indexPath.section == 2 /* BLE */ {
            ad?.deviceName = self.bleDevices[indexPath.row].name
            ad?.conntectionType = self.bleDevices[indexPath.row].interfaceType.rawValue
            ad?.connectionString = "\(self.bleDevices[indexPath.row].macAddress!)"
        }else if indexPath.section == 3 /* USB */{
            ad?.deviceName = self.usbDevices[indexPath.row].name
            ad?.conntectionType = self.usbDevices[indexPath.row].interfaceType.rawValue
            ad?.connectionString = self.usbDevices[indexPath.row].serialNumber
        }
        self.navigationController?.popViewController(animated: true)
    }
    
    func hideSpinnerAtFooter (){
        DispatchQueue.main.async { [weak self] in
            guard let strongSelf = self else { return }
            strongSelf.spinner?.stopAnimating()
        }
    }
    
    func showSpinnerAtFooter (){
        DispatchQueue.main.async { [weak self] in
            guard let strongSelf = self else { return }
            strongSelf.spinner = UIActivityIndicatorView(style: .gray)
            strongSelf.tableView.tableFooterView = strongSelf.spinner;
            strongSelf.spinner?.startAnimating()
        }
    }

}
