//
//  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()
        
        self.title = NSLocalizedString("Bluetooth Around", comment: "")
        
        self.tableView = UITableView.init(frame: self.view.frame, style: UITableView.Style.plain)
        self.tableView!.dataSource = self;
        self.tableView!.delegate = self;
        self.view.addSubview(self.tableView!)
        
        PTDispatcher.share()?.setupPeripheralFilter({(periperial, advertisement, _) -> Bool in
            
            guard let _ = periperial?.name else { return false }
            if let connectable = advertisement?[CBAdvertisementDataIsConnectable] as? NSNumber {
                if !connectable.boolValue {
                    return false
                }
            }
            return true
        })
        
        PTDispatcher.share().whenFindAllBluetooth { (array) in
            
            self.printers = array as! [PTPrinter]
            self.tableView?.reloadData()
        }
        
        // Each time you scan Bluetooth, make sure the following methods are executed
        PTDispatcher.share().whenConnectSuccess {
            SVProgressHUD.dismiss()
            PTDispatcher.share().stopScanBluetooth()
            self.navigationController!.popViewController(animated: true)
        }

    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        DispatchQueue.global().async {
            if PTDispatcher.share().getBluetoothStatus() {
                DispatchQueue.main.async {
                    PTDispatcher.share().scanBluetooth()
                }
                
            }else {
                DispatchQueue.main.async {
                    SVProgressHUD.showInfo(withStatus: NSLocalizedString("Please turn on Bluetooth", comment: ""))
                }
                
            }
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        PTDispatcher.share().stopScanBluetooth()
        PTDispatcher.share().whenConnectSuccess(nil)
        PTDispatcher.share().whenConnectFailureWithErrorBlock(nil)
    }
    
    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: UITableViewCell.CellStyle.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 printer = self.printers[indexPath.row]
        SVProgressHUD.show(withStatus: NSLocalizedString("Bluetooth is connecting", comment: ""))
        PTDispatcher.share().connect(printer)
    }
}

