//
//  PDBLEViewController.swift
//  PrinterDemo
//
//  Created by ios on 2019/9/9.
//  Copyright © 2019 XiamenHY. All rights reserved.
//

import UIKit

class PDBLEViewController: PDBaseViewController {

    private var dataSources = [PTPrinter]()
    
    lazy var tableView : UITableView = {
        let temp = UITableView.init(frame: .zero, style: .grouped)
        temp.delegate = self
        temp.dataSource = self
        temp.backgroundColor = .white
        temp.showsVerticalScrollIndicator = false
        temp.separatorStyle = UITableViewCell.SeparatorStyle.singleLine
        return temp
    }()
    
    lazy var mj_header: MJRefreshNormalHeader = {
        let temp = MJRefreshNormalHeader.init(refreshingTarget: self, refreshingAction: #selector(loadBLE))!
        temp.setTitle("Scanning nearby Bluetooth".localized, for: MJRefreshState.refreshing)
        temp.stateLabel.textColor = UIColor.gray
        temp.lastUpdatedTimeLabel.isHidden = true
        temp.activityIndicatorViewStyle = UIActivityIndicatorView.Style.gray
        return temp
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        navigationItem.title = "BLE".localized
        
        view.addSubview(tableView)
        tableView.snp.makeConstraints {
            $0.edges.equalTo(self.view.usnp.edges)
        }
        tableView.mj_header = mj_header
    }
    
    @objc func loadBLE() {
        
        if (PTDispatcher.share()?.getBluetoothStatus())! {
            PTDispatcher.share()?.stopScanBluetooth()
            dataSources.removeAll()
            self.tableView.reloadData()
            PTDispatcher.share().scanBluetooth()
            PTDispatcher.share()?.whenFindAllBluetooth({ [weak self](ptArray) in
                guard let self = self else { return }
                self.dataSources = ptArray as! [PTPrinter]
                self.mj_header.endRefreshing()
                self.tableView.reloadData()
            })
        }else {
            self.mj_header.endRefreshing()
            SVProgressHUD.showInfo(withStatus: "Please turn on Bluetooth".localized)
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        DispatchQueue.global().async {
            if PTDispatcher.share().getBluetoothStatus() {
                DispatchQueue.main.async {
                    PTDispatcher.share().scanBluetooth()
                    PTDispatcher.share()?.whenFindAllBluetooth({ [weak self](ptArray) in
                        guard let self = self else { return }
                        self.dataSources = ptArray as! [PTPrinter]
                        self.tableView.reloadData()
                    })
                }
                
            }else {
                DispatchQueue.main.async {
                    SVProgressHUD.showInfo(withStatus: "Please turn on Bluetooth".localized)
                }
                
            }
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        PTDispatcher.share().stopScanBluetooth()
        PTDispatcher.share().whenConnectSuccess(nil)
        PTDispatcher.share().whenConnectFailureWithErrorBlock(nil)
        
    }

}

extension PDBLEViewController : UITableViewDelegate,UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSources.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        var cell = tableView.dequeueReusableCell(withIdentifier: "iden")
        if cell == nil {
            cell = UITableViewCell.init(style: UITableViewCell.CellStyle.subtitle, reuseIdentifier: "iden")
        }
        cell?.textLabel?.text = dataSources[indexPath.row].name
        cell?.detailTextLabel?.text = dataSources[indexPath.row].mac
        
        cell?.textLabel?.textColor = UIColor.black
        cell?.detailTextLabel?.textColor = UIColor.titleColor
        
        return cell!
    }
    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return "Bluetooth device nearby".localized
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 45.0
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return 60.0
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        SVProgressHUD.show(withStatus: "Connecting, pls. wait".localized)
        PTDispatcher.share().connect(dataSources[indexPath.row])
        
        PTDispatcher.share().whenConnectSuccess { [weak self] in
            guard let self = self else { return }
            SVProgressHUD.showSuccess(withStatus: "Connection succeeded".localized)
            self.navigationController?.popViewController(animated: true)
        }
        
        PTDispatcher.share().whenConnectFailureWithErrorBlock { (error) in
            var errorStr: String?
            switch error {
            case .bleTimeout:
                errorStr = "Connection timeout".localized
            case .bleValidateTimeout:
                errorStr = "Vertification timeout".localized
            case .bleUnknownDevice:
                errorStr = "Unknown device".localized
            case .bleSystem:
                errorStr = "System error".localized
            case .bleValidateFail:
                errorStr = "Vertification failed".localized
            case .bleDisvocerServiceTimeout:
                errorStr = "Connection failed".localized
            default:
                break
            }
            if let temp = errorStr {
                SVProgressHUD.showError(withStatus: temp)
            }
        }
        
        
    }
}
