//
//  CPCLDemoController.swift
//  iOSPrinterDemo
//
//  Created by mellow on 2017/4/19.
//  Copyright © 2017年 Mellow. All rights reserved.
//

import Foundation

class CPCLViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    var tableView: UITableView?
    var functions: [String]?
    
    var connectButton: UIBarButtonItem?
    var disconnectButton: UIBarButtonItem?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        self.title = "CPCL Demo"
        
        self.tableView = UITableView.init(frame: self.view.frame, style: UITableViewStyle.plain)
        self.tableView!.dataSource = self;
        self.tableView!.delegate = self;
        self.view.addSubview(self.tableView!)
        
        self.functions = ["发送走纸指令","打印 HM-A300 模板电子面单[CPCL]","打印申通模板","获取纸张状态","打印指令电子面单1", "打印指令电子面单2", "打印指令电子面单3"]
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return self.functions!.count
    }
    
    open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cellIdentifier = "CPCLDemoControllerCell"
        var cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)
        
        if cell == nil {
            
            cell = UITableViewCell.init(style: UITableViewCellStyle.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 (PTDispatcher.share().printerConnected == nil) {
            AlertVC.show(message: "请先连接打印机", target: self)
        } else {
            
            if indexPath.row == 0 {
                PTDispatcher.share().send(Data.init(bytes: [0x0d,0x0a])) //向打印机发送走纸命令，打印机走纸一行
            } else if indexPath.row == 1 {
                PTDispatcher.share().send(Template.printZhongJiTemplate_CPCL())
            } else if indexPath.row == 2 {
                PTDispatcher.share().send(Template.printShenTongTemplate())
            } else if indexPath.row == 3 {
                //                PTDispatcher.share().send(Data.init(bytes: [0x1b,0x21,0x3f])) // TSPL 获取纸张
                PTDispatcher.share().whenReceiveData({ (data) in
                    print(data!)
                })
                PTDispatcher.share().send(Data.init(bytes: [0x1b,0x68]))        // CPCL 获取纸张
            } else if indexPath.row == 4 {
                PTDispatcher.share().send(PTTestCPCLSlim.printYingShangDemo())
            } else if indexPath.row == 5 {
                PTDispatcher.share().send(PTTestCPCL.testPrintDisplayLabelTwo())
            } else if indexPath.row == 6 {
                
                PTDispatcher.share().send(PTTestCPCLSlim.testPrintDisplayLabelOne())
//                PTDispatcher.share().send(PTTestCPCLSlim.autoText())
            }
            PTDispatcher.share().whenReceiveData({ (data) in
                ProgressHUD.showSuccess("打印机状态:\(data!.hexEncodedString().uppercased())")
//                print("打印机状态:\(data!.hexEncodedString().uppercased())")
            })
            PTDispatcher.share().whenUpdatePrintState({ (state) in
                if state == .success {
                    ProgressHUD.showSuccess("打印成功")
                } else if state == PTPrintState.failureLidOpen {
                    ProgressHUD.showError("打印失败（开盖）")
                } else if state == PTPrintState.failurePaperEmpty {
                    ProgressHUD.showError("打印失败（缺纸）")
                }
            })
        }
    }
    
//    func test() {
//        let cmd = PTCommandCPCL()
//        cmd.cpclLabel(withOffset: 0, hRes: 200, vRes: 200, height: 2500, quantity: 1)
//        cmd.cpclCenter()
//        cmd.cpclText(withRotate: 0, font: 8, fontSize: 0, x: 0, y: 2440, text: "打印测试")
//        cmd.cpclPrint()
//        
//        PTDispatcher.share().send(cmd.cmdData as Data!)
//    }
}

fileprivate extension Data {
    func hexEncodedString() -> String {
        return map { String(format: "%02hhx", $0) }.joined()
    }
}
