//
//  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: UITableViewStyle.plain)
        self.tableView!.dataSource = self;
        self.tableView!.delegate = self;
        self.view.addSubview(self.tableView!)
        
        PTDispatcher.share().scanBluetooth()
        PTDispatcher.share().whenFindBluetoothAll { (printerDict) in
            self.printers = Array(printerDict!.values) 
            self.tableView?.reloadData()
        }
        
        // Each time you scan Bluetooth, make sure the following methods are executed
        PTDispatcher.share().whenConnectSuccess {
            ProgressHUD.dismiss()
            PTDispatcher.share().stopScanBluetooth()
            self.navigationController!.popViewController(animated: true)
        }
        
        PTDispatcher.share().whenReceiveData { (data) in
//            print("\(data! as NSData)")
        }
        
        PTDispatcher.share().whenConnectFailureWithErrorBlock { (error) in
            ProgressHUD.dismiss()
            var errorStr: String!
            switch error {
            case .timeout:
                errorStr = NSLocalizedString("timeout", comment: "")
            case .validateTimeout:
                errorStr = NSLocalizedString("validateTimeout", comment: "")
            case .unknownDevice:
                errorStr = NSLocalizedString("unknownDevice", comment: "")
            case .system:
                errorStr = NSLocalizedString("system", comment: "")
            case .validateFail:
                errorStr = NSLocalizedString("validateFail", comment: "")
            case .disvocerServiceTimeout:
                errorStr = NSLocalizedString("disvocerServiceTimeout", comment: "")
            }
            AlertVC.show(message: errorStr, target: self)
        }
        
//        PTDispatcher.share().whenUnconnect { (userTime) in
//            print("whenUnconnect")
//        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        PTDispatcher.share().stopScanBluetooth()
        PTDispatcher.share().whenConnectSuccess(nil)
        PTDispatcher.share().whenConnectFailureWithErrorBlock(nil)
    }
    
    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";
        ProgressHUD.show(NSLocalizedString("Bluetooth is connecting", comment: ""))
        PTDispatcher.share().connect(printer)
    }
}

