//
//  PTMainViewController.swift
//  iOSPrinterDemo
//
//  Created by ios on 2019/4/24.
//  Copyright © 2019 Mellow. All rights reserved.
//

import UIKit

class PTMainViewController: UIViewController,UITableViewDelegate, UITableViewDataSource {

    var tableView: UITableView?
    var functions: [String]?
    
    var addButton: UIBarButtonItem!
    var disconnectButton: UIBarButtonItem?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.white
        
        title = NSLocalizedString("Printer command", comment: "")
        
        tableView = UITableView.init(frame: view.frame, style: UITableView.Style.plain)
        tableView!.dataSource = self;
        tableView!.delegate = self;
        view.addSubview(self.tableView!)
        
        addButton = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonItem.SystemItem.add, target: self, action: #selector(connectAction))
        disconnectButton = UIBarButtonItem.init(title: NSLocalizedString("disconnect", comment: ""), style: UIBarButtonItem.Style.plain, target: self, action: #selector(disconnectPrinter))
        
        navigationItem.rightBarButtonItem = addButton
        navigationItem.leftBarButtonItem = disconnectButton
        functions = ["CPCL", "TSPL", "ESC", "ZPL", "STAR"]
        setupDispatcherClosure()
    }

    func setupDispatcherClosure() -> Void {
        
        PTDispatcher.share().whenConnectFailureWithErrorBlock { (error) in
            SVProgressHUD.dismiss()
            var errorStr: String!
            switch error {
            case .bleTimeout:
                errorStr = NSLocalizedString("timeout", comment: "")
            case .bleValidateTimeout:
                errorStr = NSLocalizedString("validateTimeout", comment: "")
            case .bleUnknownDevice:
                errorStr = NSLocalizedString("unknownDevice", comment: "")
            case .bleSystem:
                errorStr = NSLocalizedString("system", comment: "")
            case .bleValidateFail:
                errorStr = NSLocalizedString("validateFail", comment: "")
            case .bleDisvocerServiceTimeout:
                errorStr = NSLocalizedString("disvocerServiceTimeout", comment: "")
            case .wifiTimeout:
                errorStr = NSLocalizedString("connect timeout", comment: "");
                break;
            case .wifiSocketError:
                errorStr = NSLocalizedString("Socket Connect Error", comment: "");
            default:
                errorStr = ""
                break
            }
            SVProgressHUD.showInfo(withStatus: errorStr)
        }
        
        PTDispatcher.share().whenUnconnect { [weak self](_, flag) in
            
            SVProgressHUD.showInfo(withStatus: NSLocalizedString("unconnected", comment: ""))
            self?.navigationController?.popToRootViewController(animated: true)
            PTDispatcher.share().sendSuccessBlock = nil
            PTDispatcher.share().sendFailureBlock = nil
            PTDispatcher.share().sendProgressBlock = nil
            PTDispatcher.share().connectFailBlock = nil
            PTDispatcher.share().connectSuccessBlock = nil
            PTDispatcher.share().readRSSIBlock = nil
            if flag {
                print("主动断开")
            }else {
                print("被动断开")
            }
        }
    }
    
    @objc func connectAction() {
        
        let temp = UIAlertController.init(title: NSLocalizedString("Tips", comment: ""), message: NSLocalizedString("Please select a connect type.", comment: ""), preferredStyle: .actionSheet)
        let action1 = UIAlertAction.init(title: "BLE", style: .default) { (_) in
            self.connectBLE()
        }
        let action2 = UIAlertAction.init(title: "WIFI", style: .default) { (_) in
            self.connectWiFi()
        }
        let action3 = UIAlertAction.init(title: "Auto", style: .default) { (_) in
            self.autoConnectBLE()
        }
        
        let action4 = UIAlertAction.init(title: "Cancel", style: .cancel, handler: nil)
        let actions = [action1, action2, action3, action4]
        for action in actions {
            temp.addAction(action)
        }
        temp.popoverPresentationController?.sourceView = view
        temp.popoverPresentationController?.sourceRect = CGRect.init(x: 0, y: view.bounds.height/2, width: view.bounds.width, height: 1)
        present(temp, animated: true, completion: nil)
    }
    
    private func connectBLE() {
        
        self.navigationController?.pushViewController(BluetoothVC(), animated: true)
    }
    
    private func autoConnectBLE() {
        
        self.navigationController?.pushViewController(AutoConnectBleController(), animated: true)
    }
    
    private func connectWiFi() {
        
        self.navigationController?.pushViewController(WiFiController(), animated: true)
    }
    
    @objc private func disconnectPrinter() {
        
        PTDispatcher.share().unconnectPrinter(PTDispatcher.share().printerConnected)
        
    }
    
    open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return self.functions!.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)
        }
        
        cell!.textLabel!.text = self.functions?[indexPath.row]
        
        return cell!
    }
    
    open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        tableView.deselectRow(at: indexPath, animated: true)
        
        if indexPath.row == 0 {
            let cpclController = CPCLViewController()
            navigationController?.pushViewController(cpclController, animated: true)
        } else if indexPath.row == 1 {
            let tsplController = TSPLViewController()
            navigationController?.pushViewController(tsplController, animated: true)
        } else if indexPath.row == 2 {
            let escController = ESCViewController()
            navigationController?.pushViewController(escController, animated: true)
        } else if indexPath.row == 3 {
            let zplController = ZPLViewController()
            navigationController?.pushViewController(zplController, animated: true)
        }else if indexPath.row == 4 {
            let star = STARDemoController()
            navigationController?.pushViewController(star, animated: true)
        }
    }

}
