//
//  PDTSPLViewController.swift
//  PrinterDemo
//
//  Created by ios on 2019/10/29.
//  Copyright © 2019 Printer. All rights reserved.
//

import UIKit
import PrinterSDK
import SVProgressHUD
import UniformTypeIdentifiers
import MobileCoreServices

class PDTSPLViewController: PDBaseViewController {

    lazy var tableView : UITableView = {
        let temp = UITableView.init(frame: .zero, style: .plain)
        temp.delegate = self
        temp.dataSource = self
        temp.backgroundColor = .white
        temp.rowHeight = 50.0
        temp.showsVerticalScrollIndicator = false
        temp.separatorStyle = UITableViewCell.SeparatorStyle.singleLine
        return temp
    }()
    
    private var docuemntType = PDDocumentPickerView.pdf
    private var functions = [PDSettingItem]()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        navigationItem.title = "TSPL function".localized
        
        view.addSubview(tableView)
        tableView.snp.makeConstraints {
            $0.edges.equalTo(self.view.usnp.edges)
        }
        
        loadDataSource()
    }
    
    private func loadDataSource() {
        
        functions.removeAll()
        var item : PDSettingItem
        
        item = PDSettingItem.init(title: "Self-test page Sample".localized, detailTitle: nil, target: nil, selector: #selector(PDTSPLTestFunctions.printSelfTestPage))
        functions.append(item)
        
        item = PDSettingItem.init(title: "Vector text Sample".localized, detailTitle: nil, target: nil, selector: #selector(PDTSPLTestFunctions.printVectorText))
        functions.append(item)
        
        item = PDSettingItem.init(title: "Aligned text Sample".localized, detailTitle: nil, target: self, selector: #selector(self.printAlignmentText))
        functions.append(item)
        
        item = PDSettingItem.init(title: "Dot Matrix text Sample".localized, detailTitle: nil, target: nil, selector: #selector(PDTSPLTestFunctions.printDotMatrixText))
        functions.append(item)
        
        item = PDSettingItem.init(title: "Positive Sample(Vector)".localized, detailTitle: nil, target: nil, selector: #selector(PDTSPLTestFunctions.printPositiveSampleForVector))
        functions.append(item)
        
        item = PDSettingItem.init(title: "Reverse Sample(Vector)".localized, detailTitle: nil, target: nil, selector: #selector(PDTSPLTestFunctions.printReverseSampleForVector))
        functions.append(item)
        
        item = PDSettingItem.init(title: "Positive Sample(DotMatrix)".localized, detailTitle: nil, target: nil, selector: #selector(PDTSPLTestFunctions.printPositiveSampleForDotMatrix))
        functions.append(item)
        
        item = PDSettingItem.init(title: "Reverse Sample(DotMatrix)".localized, detailTitle: nil, target: nil, selector: #selector(PDTSPLTestFunctions.printReverseSampleForDotMatrix))
        functions.append(item)
        
        item = PDSettingItem.init(title: "Device Status Sample".localized, detailTitle: nil, target: nil, selector: #selector(PDTSPLTestFunctions.getPrinterStatus))
        functions.append(item)
        
        item = PDSettingItem.init(title: "Barcode Sample".localized, detailTitle: nil, target: nil, selector: #selector(PDTSPLTestFunctions.printBarcode))
        functions.append(item)
        
        item = PDSettingItem.init(title: "Bitmap Sample".localized, detailTitle: nil, target: self, selector: #selector(self.pushSystenPhoto))
        functions.append(item)
        
        item = PDSettingItem.init(title: "PDF Print".localized, detailTitle: nil, target: self, selector: #selector(self.selectPDFFiles))
        functions.append(item)
        
        item = PDSettingItem.init(title: "Command File Print".localized, detailTitle: nil, target: self, selector: #selector(self.selectDocument))
        functions.append(item)
        
        item = PDSettingItem.init(title: "Model Sample".localized, detailTitle: nil, target: nil, selector: #selector(PDTSPLTestFunctions.testModel1))
        functions.append(item)
        
        item = PDSettingItem.init(title: "Set Receipt Paper".localized, detailTitle: nil, target: nil, selector: #selector(PDTSPLTestFunctions.setReceiptSample))
        functions.append(item)
        
        item = PDSettingItem.init(title: "Set Label Paper".localized, detailTitle: nil, target: nil, selector: #selector(PDTSPLTestFunctions.setLabelSample))
        functions.append(item)
        
        item = PDSettingItem.init(title: "Set Black Mark Paper".localized, detailTitle: nil, target: nil, selector: #selector(PDTSPLTestFunctions.setBlackMarkSample))
        functions.append(item)
        
        
    }
    

}

extension PDTSPLViewController : UITableViewDelegate,UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return functions.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        var cell = tableView.dequeueReusableCell(withIdentifier: "iden")
        if cell == nil {
            cell = UITableViewCell.init(style: UITableViewCell.CellStyle.subtitle, reuseIdentifier: "iden")
        }
        cell?.textLabel?.text = functions[indexPath.row].title
        cell?.textLabel?.textColor = UIColor.black
        
        return cell!
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        let action = functions[indexPath.row]
        if let target = action.target {
            if let selector = action.selector {
                target.perform(selector)
            }
        }else {
            if let selector = action.selector {
                PDTSPLTestFunctions.perform(selector)
            }
        }
    }
}

extension PDTSPLViewController {
    
    //MARK:print image
    @objc func pushSystenPhoto() {
        
        let photoPickerVC = PDPhotoListViewController.init(with: PTCommandType.TSPL)
        navigationController?.pushViewController(photoPickerVC, animated: true)
    }
    
    @objc private func printAlignmentText() {
        self.navigationController?.pushViewController(TSPLAlignmentViewController(), animated: true)
    }
    
    @objc private func selectDocument() {
        self.docuemntType = PDDocumentPickerView.commandDocument
        let picker = UIDocumentPickerViewController.init(documentTypes: ["public.data"], in: .import)
        picker.delegate = self
        picker.modalPresentationStyle = .fullScreen
        if #available(iOS 11.0, *) {
            picker.allowsMultipleSelection = false
        }
        self.present(picker, animated: true, completion: nil)
    }
    
    @objc private func selectPDFFiles() {
        
        var picker: UIDocumentPickerViewController
        if #available(iOS 14, *) {
            picker = UIDocumentPickerViewController.init(
                forOpeningContentTypes: [
                    UTType.init(tag: "pdf", tagClass: UTTagClass.filenameExtension, conformingTo: UTType.data)!
                ], asCopy: true)
        }else {
            picker = UIDocumentPickerViewController.init(documentTypes: ["public.data"], in: .import)
        }

        self.docuemntType = PDDocumentPickerView.pdf
        picker.delegate = self
        picker.modalPresentationStyle = .overFullScreen
        self.present(picker, animated: true, completion: nil)
    }
}

extension PDTSPLViewController: UIDocumentPickerDelegate {
    
    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {
        
        sendData(from: url)
    }
    
    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        
        sendData(from: urls[0])
    }
    
    func sendData(from url: URL) -> Void {
        
        switch self.docuemntType {
            case .commandDocument:
                self.selectCmdPrint(url)
            case .firmwareBin:
                self.updatePrinterFirmware(url)
            case .pdf:
                self.selectPDFPrint(url, .TSPL)
        }
    }
}

struct PDPrinterTSPLStatusOptionSet : OptionSet,CustomStringConvertible {
    
    var rawValue: UInt8
    typealias RawValue = UInt8
    
    static let headOpen = PDPrinterTSPLStatusOptionSet.init(rawValue: 1<<0)
    static let paperJam = PDPrinterTSPLStatusOptionSet.init(rawValue: 1<<1)
    static let noPaper = PDPrinterTSPLStatusOptionSet.init(rawValue: 1<<2)
//    static let noRibbon = PDPrinterTSPLStatusOptionSet.init(rawValue: 1<<3)
    static let pause = PDPrinterTSPLStatusOptionSet.init(rawValue: 1<<4)
    static let printing = PDPrinterTSPLStatusOptionSet.init(rawValue: 1<<5)
    static let coverOpened = PDPrinterTSPLStatusOptionSet.init(rawValue: 1<<6)
    static let high = PDPrinterTSPLStatusOptionSet.init(rawValue: 1<<7)
    
    var description: String {
        
        var messages = [String]()
        if contains(.headOpen) {
            messages.append("Open".localized)
        }
        
        if contains(.paperJam) {
            messages.append("Paper jam".localized)
        }
        
        if contains(.noPaper) {
            messages.append("Out of paper".localized)
        }
        
        if contains(.pause) {
            messages.append("Pause".localized)
        }
        
        if contains(.printing) {
            messages.append("Printing".localized)
        }

        if contains(.coverOpened) {
            messages.append("Open".localized)
        }

        if contains(.high) {
            messages.append("High".localized)
        }
        
        if messages.count == 0 {
            messages.append("Ready".localized)
        }
        return  messages.joined(separator: "--")
    }
}
