//
//  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 = [NSLocalizedString("Send the command of paper feed", comment: ""), NSLocalizedString("Print electronic waybill", comment: ""), NSLocalizedString("Print STO template", comment: ""), NSLocalizedString("Get paper status", comment: ""), NSLocalizedString("Print electronic waybill 1", comment: ""),NSLocalizedString("Print electronic waybill 2", comment: ""),NSLocalizedString("Print electronic waybill 3", comment: ""),NSLocalizedString("Print STO electronic waybill", 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: "")]
    }
    
    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: 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: NSLocalizedString("Please connect the printer", comment: ""), target: self)
        } else {
            
            if indexPath.row == 0 {
                //the printer take the paper line
                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 {
                // 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 {
                        ProgressHUD.showError(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()] {
                        ProgressHUD.showSuccess(statusStr)
                    }else {
                        ProgressHUD.showError(NSLocalizedString("Unknown paper status", comment: ""))
                    }
                })
                
            } else if indexPath.row == 4 {
                PTDispatcher.share().send(PTTestCPCLSlim.autoText())
            } else if indexPath.row == 5 {
                
                PTDispatcher.share().send(PTTestCPCL.testPrintDisplayLabelTwo())
            } else if indexPath.row == 6 {
                PTDispatcher.share().send(PTTestCPCLSlim.testPrintDisplayLabelOne())
            }else if indexPath.row == 7 {
                PTDispatcher.share().send(Template.printZhongTongTemplate())
            }else if indexPath.row == 8 {
                PTDispatcher.share().send(PTTestCPCLSlim.printImageViewTemplate_CPCL())
                PTDispatcher.share().whenSendProgressUpdate({ (progress) in
                    if progress!.intValue == 1 {
                        ProgressHUD.dismiss()
                    }else {
                        ProgressHUD.show("sending")
                    }
                })
            }else if indexPath.row == 9 {
                PTDispatcher.share().send(PTTestCPCLSlim.setPaperWithReceipt())
            }else if indexPath.row == 10 {
                PTDispatcher.share().send(PTTestCPCLSlim.setPaperWithLabel())
            }else if indexPath.row == 11 {
                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!)
            }
            
            
            PTDispatcher.share().whenSendSuccess({ (usedTime) in
                print("Send Data Success:\(usedTime!)")
            })
            PTDispatcher.share().whenUpdatePrintState({ (state) in
                
                if state == .success {
                    ProgressHUD.showSuccess(NSLocalizedString("print Success", comment: ""))
                } else if state == PTPrintState.failureLidOpen {
                    ProgressHUD.showError(NSLocalizedString("print fail（LidOpe）", comment: ""))
                } else if state == PTPrintState.failurePaperEmpty {
                    ProgressHUD.showError(NSLocalizedString("print fail（PaperEmpty）", comment: ""))
                }
            })
        }
    }
}

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