//
//  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]?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.title = "CPCL Demo"
        
        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!)
        
        self.functions = [NSLocalizedString("Text test", comment: ""), NSLocalizedString("Print electronic waybill", comment: ""), NSLocalizedString("Print STO template", comment: ""), NSLocalizedString("Get paper status", comment: ""), NSLocalizedString("Thai automatic line break test", comment: ""),NSLocalizedString("Normal direction printing", comment: ""),NSLocalizedString("Print after rotating 90 degrees", comment: ""),NSLocalizedString("Print after rotating 180 degrees", comment: ""),NSLocalizedString("Print bitmap", comment: ""),NSLocalizedString("Set continuous paper", comment: ""),NSLocalizedString("Set label paper", comment: ""),NSLocalizedString("testInverseLine", comment: ""),NSLocalizedString("Turn on print status callback", comment: ""),NSLocalizedString("Turn off print status callback", comment: ""),NSLocalizedString("Print background text", comment: ""),NSLocalizedString("Get the printer serial number", comment: ""),NSLocalizedString("Automatic line feed printing", comment: ""),NSLocalizedString("Automatic line feed after exceeding the safe height", comment: ""),NSLocalizedString("Get printer model name", comment: "")]
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        PTDispatcher.share().whenUpdatePrintState(nil)
        PTDispatcher.share().whenReceiveData(nil)
    }
    
    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: 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 (PTDispatcher.share().printerConnected == nil) {
            AlertVC.show(message: NSLocalizedString("Please connect the printer", comment: ""), target: self)
        } else {
        
            if indexPath.row == 0 {
                
                let test = PTPrintTextViewController()
                test.commandType = .CPCL
                navigationController?.pushViewController(test, animated: true)
                
            } else if indexPath.row == 1 {
                SVProgressHUD.show()
                PTDispatcher.share().send(PTTestCPCL.testPrintDisplayLabelTwo())
            } else if indexPath.row == 2 {
                SVProgressHUD.show()
                PTDispatcher.share().send(Template.printShenTongTemplate())
                
            } else if indexPath.row == 3 {
                
                // CPCL Get paper status
                let cpcl = PTCommandCPCL()
                cpcl.cpclGetPaperStatus()
                PTDispatcher.share().send(cpcl.cmdData as Data)
                PTDispatcher.share().whenReceiveData({ (data) in
                    guard let tempData = data else {
                        SVProgressHUD.showInfo(withStatus: NSLocalizedString("Receive data is empty", comment: ""))
                        return }
                    if tempData.count != 1 {
                        return
                    }
                    let dic = [
                        "00": NSLocalizedString("Ready, lid paper", comment: ""),
                        "01": NSLocalizedString("Go paper or print", comment: ""),
                        "02": NSLocalizedString("Out of paper", comment: ""),
                        "04": NSLocalizedString("Open the lid with paper", comment: ""),
                        "06": NSLocalizedString("Open the lid out of paper", comment: "")]
                    if let statusStr = dic[tempData.hexEncodedString()] {
                        SVProgressHUD.showSuccess(withStatus: statusStr)
                    }else {
                        SVProgressHUD.showInfo(withStatus: NSLocalizedString("Unknown paper status", comment: ""))
                    }
                })
                
            } else if indexPath.row == 4 {
                
                let test = PTThaiAutoViewController()
                navigationController?.pushViewController(test, animated: true)
                
            } else if indexPath.row == 5 {
                SVProgressHUD.show()
                PTDispatcher.share().send(PTTestCPCL.testCaseFirst())
                
            } else if indexPath.row == 6 {
                SVProgressHUD.show()
                PTDispatcher.share().send(PTTestCPCL.testCaseSecond())
                
            }else if indexPath.row == 7 {
                SVProgressHUD.show()
                PTDispatcher.share().send(PTTestCPCL.testCaseThird())
                
            }else if indexPath.row == 8 {
                
                let printImageVC = PTPrintBitmapController()
                printImageVC.commandType = PTCommandType.CPCL
                navigationController?.pushViewController(printImageVC, animated: true)
                
            }else if indexPath.row == 9 {
                SVProgressHUD.show()
                PTDispatcher.share().send(PTTestCPCLSlim.setPaperWithReceipt())
                
            }else if indexPath.row == 10 {
                SVProgressHUD.show()
                PTDispatcher.share().send(PTTestCPCLSlim.setPaperWithLabel())
                
            }else if indexPath.row == 11 {
                SVProgressHUD.show()
                PTDispatcher.share().send(PTTestCPCLSlim.testInverseLine())
                
            }else if indexPath.row == 12 {
                
                let cpcl = PTCommandCPCL()
                cpcl.cpclTurn(onPrintStatusCallBack: true)
                PTDispatcher.share().send(cpcl.cmdData as Data)
                
            }else if indexPath.row == 13 {
                
                let cpcl = PTCommandCPCL()
                cpcl.cpclTurn(onPrintStatusCallBack: false)
                PTDispatcher.share().send(cpcl.cmdData as Data)
                
            }else if indexPath.row == 14 {
                SVProgressHUD.show()
                PTDispatcher.share().send(PTTestCPCLSlim.printBackGroundText())
                
            }else if indexPath.row == 15 {
                
                let cpcl = PTCommandCPCL()
                cpcl.cpclGetPrinterSN()
                PTDispatcher.share().send(cpcl.cmdData as Data)
                PTDispatcher.share().whenReceiveData({ (data) in
                    guard let tempData = data else {
                        SVProgressHUD.showInfo(withStatus: NSLocalizedString("Receive data is empty", comment: ""))
                        return }
                    let hexString = tempData.hexEncodedString()
                    let rRange = hexString.index(hexString.startIndex, offsetBy: 2)
                    let rString = hexString[..<rRange]
                    
                    let bRange = hexString.index(hexString.endIndex, offsetBy: -2)
                    let bString = hexString[bRange..<hexString.endIndex]
                    
                    if rString != "5f" && bString != "00" {
                        return
                    }
                    let result = hexString[rRange..<bRange]
                    let SN = HexData.hyConvertHexStr(to: String.init(result))
                    SVProgressHUD.showSuccess(withStatus: SN)
                })
                PTDispatcher.share()?.whenSendSuccess({
                    
                })
            }else if indexPath.row == 16 {
                
                PTTestCPCL.automaticLineFeedPrintingText()
                
            }else if indexPath.row == 17 {
                PTTestCPCL.automaticLineFeedAfterExceedingSafeHeight()
                
            }else if indexPath.row == 18 {
                PTTestCPCL.getPrinterModelName()
            }
        
            PTDispatcher.share()?.whenSendSuccess({
                SVProgressHUD.dismiss()
            })
            
            PTDispatcher.share().whenUpdatePrintState({ (state) in
                if state == .success {
                    SVProgressHUD.showSuccess(withStatus: NSLocalizedString("print Success", comment: ""))
                    
                } else if state == PTPrintState.failureLidOpen {
                    SVProgressHUD.showInfo(withStatus: NSLocalizedString("print fail（LidOpe）", comment: ""))
                    
                } else if state == PTPrintState.failurePaperEmpty {
                    SVProgressHUD.showInfo(withStatus: NSLocalizedString("print fail（PaperEmpty）", comment: ""))
                }
            })
        }
    }
}

extension Data {
    func hexEncodedString() -> String {
        return map { String(format: "%02hhx", $0) }.joined()
    }
    
    var hexString : String {
        return self.map({ String.init(format: "%02x", $0)}).joined(separator: " ")
    }
}
