//
//  SearchPrinterViewController.swift
//  iPOS
//
//  Created by BBC on 12/06/17.
//  Copyright © 2017 BBC. All rights reserved.
//

import Foundation

protocol SearchPrinterViewDelegate {
    func selectedPrinter(printerName: String, printerIp:String)
}

class SearchPrinterViewController: UIViewController, UITableViewDataSource, UITableViewDelegate,Epos2DiscoveryDelegate {
    
    @IBOutlet weak var startButton: UIButton!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var stopButton: UIButton!
    
    var printerList: [Epos2DeviceInfo] = []
    var filterOption: Epos2FilterOption = Epos2FilterOption()
    var delegate: SearchPrinterViewDelegate?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.dataSource = self
        self.tableView.delegate = self
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        changeControlStatus(status: true)
    }
    
    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        while Epos2Discovery.stop() == EPOS2_ERR_PROCESSING.rawValue {
            // retry stop function
        }
        printerList.removeAll()
    }
    
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return false
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.printerList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = self.tableView.dequeueReusableCell(withIdentifier: "cell") as! PrinterCustomCell
        cell.printerName.text = self.printerList[indexPath.row].deviceName
        cell.printerName.font = UIFont.boldSystemFont(ofSize: cell.printerName.font.pointSize)
        if self.printerList[indexPath.row].ipAddress != nil && !self.printerList[indexPath.row].ipAddress.isEmpty{
            cell.wifiImage.image = UIImage.init(named: "wi-fi.png")
            cell.printerAddress.text = self.printerList[indexPath.row].ipAddress
        }
        else{
            cell.wifiImage.image = nil
        }
        if self.printerList[indexPath.row].bdAddress != nil && !self.printerList[indexPath.row].bdAddress.isEmpty{
            cell.bluetoothImage.image = UIImage.init(named: "bluetooth.png")
            cell.printerAddress.text = self.printerList[indexPath.row].bdAddress
        }
        else{
            cell.bluetoothImage.image = nil
            
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if delegate != nil{
            let printer = printerList[indexPath.row]
            if let ip = printer.ipAddress, ip.isEmpty == false{
                delegate!.selectedPrinter(printerName: printer.deviceName, printerIp: printer.ipAddress)
            }
            else if let bt = printer.bdAddress, bt.isEmpty == false{
                delegate!.selectedPrinter(printerName: printer.deviceName, printerIp: printer.bdAddress)
            }
            else{
                delegate!.selectedPrinter(printerName: printerList[indexPath.row].deviceName, printerIp: printerList[indexPath.row].target)
            }
        }
    }
    
    @IBAction func startButton_Click(_ sender: Any) {
        self.printerList.removeAll()
        self.filterOption.deviceType = EPOS2_TYPE_PRINTER.rawValue
        self.filterOption.portType = EPOS2_PORTTYPE_ALL.rawValue
        changeControlStatus(status: false)
        let result = Epos2Discovery.start(filterOption, delegate: self)
        if result != EPOS2_SUCCESS.rawValue {
            //ShowMsg showErrorEpos(result, method: "start")
        }
        self.tableView.reloadData()
    }
    
    func changeControlStatus(status: Bool){
        self.startButton.isEnabled = status
        self.stopButton.isEnabled = !status
    }
    
    @IBAction func stopButton_Click(_ sender: Any) {
        changeControlStatus(status: true)
        while Epos2Discovery.stop() == EPOS2_ERR_PROCESSING.rawValue {
            // retry stop function
        }
    }
    
    func onDiscovery(_ deviceInfo: Epos2DeviceInfo!) {
        printerList.append(deviceInfo)
        self.tableView.reloadData()
    }
}
