//
//  BluetoothVC.swift
//  BluetoothDemo
//
//  Created by midmirror on 16/10/28.
//  Copyright © 2016年 Mellow. All rights reserved.
//

import UIKit

class BluetoothVC: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    var tableView: UITableView?
    var printers = [PTPrinter]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        self.title = "蓝牙扫描"
        
        self.tableView = UITableView.init(frame: self.view.frame, style: UITableViewStyle.plain)
        self.tableView!.dataSource = self;
        self.tableView!.delegate = self;
        self.view.addSubview(self.tableView!)
        
        PTDispatcher.share().scanBluetooth()
        PTDispatcher.share().whenFindBluetoothAll { (printerDict: [AnyHashable : Any]?) in
            
            self.printers = Array(printerDict!.values) as! [PTPrinter]
            self.tableView?.reloadData()
        }
        
        // 要确保每次 scanBluetooth 时，以下所有方法都执行到。
        
        PTDispatcher.share().whenConnectSuccess {
            
            PTDispatcher.share().stopScanBluetooth()
            self.navigationController!.popViewController(animated: true)
        }
        
        PTDispatcher.share().whenConnectFailure {
            
            AlertVC.show(message: "连接失败", target: self)
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return self.printers.count
    }
    
    open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cellIdentifier = "BluetoothVC"
        var cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)
        
        if cell == nil {
            cell = UITableViewCell.init(style: UITableViewCellStyle.subtitle, reuseIdentifier: cellIdentifier)
        }
        
        let printer = self.printers[indexPath.row]
        cell!.textLabel!.text = printer.name
        cell!.detailTextLabel!.text = printer.mac
        
        return cell!
    }
    
    open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        tableView.deselectRow(at: indexPath, animated: true)
        let cell = tableView.cellForRow(at: indexPath)
        cell?.accessoryType = UITableViewCellAccessoryType.checkmark
        let printer = self.printers[indexPath.row]
        printer.model = "QNG-LBO-I4R-HOV";
        PTDispatcher.share().connect(printer)
    }
}

