//
//  TextTSPLDemo.swift
//  iOSPrinterDemo
//
//  Created by ios on 2017/12/21.
//  Copyright © 2017年 Mellow. All rights reserved.
//

import UIKit

class TextTSPLDemo: NSObject {
    
    
    func selfTextPage() {
        
        let cmd = PTCommandTSPL.init()
        cmd.setCLS()
        cmd.selfTest()
        PrinterPort.send(Data: cmd.cmdData as Data)
    }
    
    func testText() {

        let cmd = PTCommandTSPL.init()
        cmd.encoding = CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(CFStringEncodings.big5.rawValue))
        cmd.setCLS()
        cmd.setPrintAreaSizeWithWidth(90, height: 110)
        cmd.setOffsetWithDistance(-11)
        cmd.setFontBold(true)
        cmd.appendText(withXpos: 100, yPos: 400, font: PTTSCTextFontStyle.style1, rotation: PTTSCStyleRotation.rotation0, xMultiplication: 50, yMultiplication: 50, text: "測試中文標題")
//        cmd.appendText(withXpos: <#T##Int#>, yPos: <#T##Int#>, font: <#T##PTTSCTextFontStyle#>, rotation: <#T##PTTSCStyleRotation#>, xMultiplication: <#T##Int#>, yMultiplication: <#T##Int#>, text: <#T##String!#>)
        cmd.appendText(withXpos: 150, yPos: 500, font: PTTSCTextFontStyle.style1, rotation: PTTSCStyleRotation.rotation0, xMultiplication: 1, yMultiplication: 1, text: "Jimmy Wang")
        cmd.appendText(withXpos: 100, yPos: 550, font: PTTSCTextFontStyle.style1, rotation: PTTSCStyleRotation.rotation0, xMultiplication: 50, yMultiplication: 50, text: "Perfect Go.")
        cmd.appendText(withXpos: 100, yPos: 600, font: PTTSCTextFontStyle.style1, rotation: PTTSCStyleRotation.rotation0, xMultiplication: 50, yMultiplication: 50, text: "Technicl Service Manager")
        cmd.printQRcode(withXPos: 450, yPos: 350, eccLevel: PTTSCQRcodeEcclevel.H, cellWidth: PTTSCQRcodeWidth.width7, mode: PTTSCQRCodeMode.manual, rotation: PTTSCStyleRotation.rotation0, model: PTTSCQRCodeModel.M2, mask: PTTSCQRcodeMask.S0, context: "_http://www.perfect.tw/")
        cmd.print(withSets: 1, copies: 1)
        PrinterPort.send(Data: cmd.cmdData as Data)
        
    }
    
    func testQRcode() {
        let cmd = PTCommandTSPL.init()
        cmd.setCLS()
        cmd.printQRcode(withXPos: 100, yPos: 100, eccLevel: PTTSCQRcodeEcclevel.H, cellWidth: PTTSCQRcodeWidth.width7, mode: PTTSCQRCodeMode.manual, rotation: PTTSCStyleRotation.rotation0, model: PTTSCQRCodeModel.M1, mask: PTTSCQRcodeMask.S1, context: "Hello World")
        cmd.print(withSets: 1, copies: 1)
        PrinterPort.send(Data: cmd.cmdData as Data)
    }
    
    func testBarcode() {
        let cmd = PTCommandTSPL.init()
        cmd.setCLS()
        cmd.printBarcode(withXPos: 100, yPos: 100, type: PTTSCBarcodeStyle.style128, height: 100, readable: PTTSCBarcodeReadbleStyle.human, rotation: PTTSCStyleRotation.rotation0, ratio: PTTSCBarcodeRatio.ratio3, context: "1234567890")
        
        cmd.print(withSets: 1, copies: 1)
        PrinterPort.send(Data: cmd.cmdData as Data)
    }
    
    func generateRenderingImage() {
        
        let image = UIImage.init(named: "DLTest3.png")
        
        guard let printImage = image else {
            SVProgressHUD.showInfo(withStatus: NSLocalizedString("Image does not exist", comment: ""))
            return
        }
        
        //你选择哪种模式打印图片，这边的mode就选哪种
        guard let renderImage = PTBitmap.generateRendering(with: printImage.cgImage, mode: PTBitmapMode.binary) else {return}
        
        guard let imageData = renderImage.pngData() else {return}
        
        let documents = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first!
        print(documents)
        let url = URL.init(fileURLWithPath: documents + "/DL.png")
        
        do {
            try imageData.write(to: url)
        } catch {
            print(error)
        }
        
    }
    
    func testPrintBitmapForUncompress() {
        
        let image = UIImage.init(named: "DL-Test.png")

        guard let printImage = image else {
            SVProgressHUD.showInfo(withStatus: NSLocalizedString("Image does not exist", comment: ""))
            return
        }

        let imageWidth = Int((printImage.size.width.truncatingRemainder(dividingBy: 8))) == 0 ? Int((printImage.size.width / 8)) : Int((printImage.size.width + 8) / 8)

        let imageHeight = Int((printImage.size.height.truncatingRemainder(dividingBy: 8))) == 0 ? Int((printImage.size.height / 8)) : Int((printImage.size.height + 8) / 8)

        let cmd = PTCommandTSPL.init()
        cmd.setCLS()
        //这边指的是纸的毫米，不是像素点
        cmd.setPrintAreaSizeWithWidth(imageWidth, height: imageHeight)
        //mode 和 compress决定是否压缩
        let ret = cmd.addBitmap(withXPos: 0, yPos: 0, mode: PTTSCBitmapMode.OR, image: printImage.cgImage, bitmapMode: PTBitmapMode.dithering, compress: PTBitmapCompressMode.none)
        cmd.print(withSets: 1, copies: 1)
        if ret {
            PrinterPort.send(Data: cmd.cmdData as Data)

        }else {
            SVProgressHUD.showInfo(withStatus: NSLocalizedString("The data exceeds the cache and cannot be printed", comment: ""))
        }
    }
    
    func testPrintBitmapForCompress() {
        
        let image = UIImage.init(named: "WechatIMG429.png")

        guard let printImage = image else {
            SVProgressHUD.showInfo(withStatus: NSLocalizedString("Image does not exist", comment: ""))
            return
        }

        let imageWidth = Int((printImage.size.width.truncatingRemainder(dividingBy: 8))) == 0 ? Int((printImage.size.width / 8)) : Int((printImage.size.width + 8) / 8)

        let imageHeight = Int((printImage.size.height.truncatingRemainder(dividingBy: 8))) == 0 ? Int((printImage.size.height / 8)) : Int((printImage.size.height + 8) / 8)

        let cmd = PTCommandTSPL.init()
        cmd.setCLS()
        //这边指的是纸的毫米，不是像素点
        cmd.setPrintAreaSizeWithWidth(imageWidth, height: imageHeight)
        //mode ：16 17 18
        let ret = cmd.addBitmap(withXPos: 0, yPos: 0, mode: PTTSCBitmapMode.orCompress, image: printImage.cgImage, bitmapMode: PTBitmapMode.dithering, compress: PTBitmapCompressMode.LZO)
        cmd.setPrintDensity(PTTSCPrintDensity.density8)
        cmd.print(withSets: 1, copies: 2)
        if ret {
            PrinterPort.send(Data: cmd.cmdData as Data)

        }else {
            SVProgressHUD.showInfo(withStatus: NSLocalizedString("The data exceeds the cache and cannot be printed", comment: ""))
        }
    }
    
    func testPrintBox() {
        let cmd = PTCommandTSPL.init()
        cmd.setCLS()
        cmd.setBoxWithXStart(100, yStart: 100, xEnd: 500, yEnd: 500, thickness: 3)
        cmd.print(withSets: 1, copies: 1)
        PrinterPort.send(Data: cmd.cmdData as Data)
    }
    
    func testPrintCircle() {
        let cmd = PTCommandTSPL.init()
        cmd.setCLS()
        cmd.setCircleWithXStart(100, yStart: 100, diameter: 500, thickness: 3)
        cmd.print(withSets: 1, copies: 1)
        PrinterPort.send(Data: cmd.cmdData as Data)
    }
    
    func testPrintBar() {
        let cmd = PTCommandTSPL.init()
        cmd.setCLS()
        cmd.drawBar(withXPos: 200, yPos: 200, width: 500, height: 10)
        cmd.print(withSets: 1, copies: 1)
        PrinterPort.send(Data: cmd.cmdData as Data)
    }
    
    func getPrinterStatus() {
        
        let tspl = PTCommandTSPL.init()
        tspl.setCLS()
        tspl.getPrinterStatus()
        PTDispatcher.share().send(tspl.cmdData as Data)
        PTDispatcher.share().whenReceiveData { (data) in
            guard let temp = data else {
                return
            }
            if temp.count > 1 {
                return
            }
            let byte = [UInt8](temp)

            var state = ""

            if byte[0] & 1 == 1 {
                state += "开盖"
            }else {
                state += "合盖"
            }

            if byte[0] & 4 == 4 {
                state += "缺纸"
            }else {
                state += "有纸"
            }

            if byte[0] & 128 == 128 {
                state += "高温"
            }else {
                state += "常温"
            }
            SVProgressHUD.showSuccess(withStatus: state)
        }
    }
    
    func openPrinterStateAutomaticBack() {
        let cmd = PTCommandTSPL.init()
        cmd.setCLS()
        cmd.setPrinterStateAutomaticBackWithStatus(true)
        PTDispatcher.share().send(cmd.cmdData as Data)
    }
    
    func closePrinterStateAutomaticBack() {
        let cmd = PTCommandTSPL.init()
        cmd.setCLS()
        cmd.setPrinterStateAutomaticBackWithStatus(false)
        PTDispatcher.share().send(cmd.cmdData as Data)
    }
    
    func test200TimesBitmapData() {
        
        let image = UIImage.init(named: "DLTest3.png")
        guard let printImage = image else {
            SVProgressHUD.showInfo(withStatus: NSLocalizedString("Image does not exist", comment: ""))
            return
        }
        let imageWidth = Int((printImage.size.width.truncatingRemainder(dividingBy: 8))) == 0 ? Int((printImage.size.width / 8)) : Int((printImage.size.width + 8) / 8)
        let imageHeight = Int((printImage.size.height.truncatingRemainder(dividingBy: 8))) == 0 ? Int((printImage.size.height / 8)) : Int((printImage.size.height + 8) / 8)
        let cmd = PTCommandTSPL.init()
        cmd.setCLS()

        //这边指的是纸的毫米，不是像素点
        cmd.setPrintAreaSizeWithWidth(imageWidth, height: imageHeight)
        //mode ：16 17 18
        cmd.setPrintDensity(PTTSCPrintDensity.density10)
        cmd.setPrinterStateAutomaticBackWithStatus(true)
        let _ = cmd.addBitmap(withXPos: 0, yPos: 0, mode: PTTSCBitmapMode.orCompress, image: printImage.cgImage, bitmapMode: PTBitmapMode.dithering, compress: PTBitmapCompressMode.LZO)
        cmd.print(withSets: 1, copies: 1)
        PTDispatcher.share().send(cmd.cmdData as Data)
        var counter = 10
        SVProgressHUD.show(withStatus: "Please wait while sending. . .")
        PTDispatcher.share().whenSendSuccess {
            print("---------------------数据发送成功---------------------")
//            print("计数器 == \(counter)")
//            counter -= 1
//            if counter > 0 {
//                self.testCyclePrint()
//            }else {
//                print("打印完成")
//            }
        }

        PTDispatcher.share().whenReceiveData { (backData) in

            guard let tempData = backData else { return }

            if tempData.count >= 10 {

                let headString = tempData[0...3].map({String.init(format: "%02x", $0)}).joined()
                let endData = tempData[9]

                if headString == "aabbccdd" && endData == UInt8(0) {

                    let numString = tempData[4...7].map({String.init(format: "%02x", $0)}).joined()
                    var state = ""
                    let byte = tempData[8]
                    if byte & 1 == 1 {
                        state += "开盖"
                    }

                    if byte & 2 == 2 {
                        state += "卡纸"
                    }

                    if byte & 4 == 4 {
                        state += "缺纸"
                    }
                    if byte & 128 == 128 {
                        state += "高温"
                    }
                    if state.isEmpty {

                        if numString == "ffffffff" || numString == "00000000" {
                            print("---------------------计数器 == \(counter)")
                            counter -= 1
                            if counter > 0 {

                                if PTDispatcher.share().printerConnected == nil {
                                    SVProgressHUD.showInfo(withStatus: "请连接打印机")
                                }else {
                                    self.testCyclePrint()
                                }

                            }else {
                                print("全部数据打印完成")
                                SVProgressHUD.showSuccess(withStatus: "全部数据打印完成")
                            }

                        }else {
                            print("开始计算张数")
                        }

                    }else {
                        print("打印机故障状态 == \(state)")
                        SVProgressHUD.showInfo(withStatus: state)
                    }
                }
            }
        }
        
    }
    
    func testCyclePrint() {
        
        let image = UIImage.init(named: "DLTest3.png")
        guard let printImage = image else {
            SVProgressHUD.showInfo(withStatus: NSLocalizedString("Image does not exist", comment: ""))
            return
        }
        
        let imageWidth = Int((printImage.size.width.truncatingRemainder(dividingBy: 8))) == 0 ? Int((printImage.size.width / 8)) : Int((printImage.size.width + 8) / 8)
        
        let imageHeight = Int((printImage.size.height.truncatingRemainder(dividingBy: 8))) == 0 ? Int((printImage.size.height / 8)) : Int((printImage.size.height + 8) / 8)
        
        let cmd = PTCommandTSPL.init()
        cmd.setCLS()
        //这边指的是纸的毫米，不是像素点
        cmd.setPrintAreaSizeWithWidth(imageWidth, height: imageHeight)
        cmd.setPrinterStateAutomaticBackWithStatus(true)
        //mode ：16 17 18
        let _ = cmd.addBitmap(withXPos: 0, yPos: 0, mode: PTTSCBitmapMode.orCompress, image: printImage.cgImage, bitmapMode: PTBitmapMode.dithering, compress: PTBitmapCompressMode.LZO)
        cmd.print(withSets: 1, copies: 1)
        PTDispatcher.share().send(cmd.cmdData as Data)
    }
    
    
    func getPrinterName() {
        let cmd = PTCommandCommon.init()
        cmd.getPrinterModelName()
        PTDispatcher.share()?.send(cmd.cmdData as Data)
        PTDispatcher.share()?.whenReceiveData({ (data) in
            //回的数据格式<51333142 5400>
            guard var tempData = data else { return }
            guard let name = PTEncode.decodeString(with: tempData[0...tempData.count - 2]) else { return }
            SVProgressHUD.showSuccess(withStatus: name)
            
        })
        
    }
    
}


