//
//  LabelPrinter.swift
//  //  iPOS
//
//  Created by bbc on 23.02.2017.
//  Copyright © 2017 BBC. All rights reserved.
//

import Foundation
import UIKit

class EpsonLabelPrinter: NSObject, LWPrintDelegate {
    
    var printerInfo: [String: AnyObject]?
    let lwPrint: LWPrint = LWPrint()
    var viewController: UIViewController!
    var dataProvider: LWPrintDataProvider?
    
    func printWorkOrderLabel(viewController: UIViewController, workOrder: WorkOrder){
        self.viewController = viewController
        self.dataProvider = LWWorkOrderDataProvider(workOrder: workOrder)
        performPrint()
    }
    
    // MARK: LWPrintDelegate
    func lwPrint(_ lwPrint: LWPrint!, didChangePrintOperationPhase jobPhase: LWPrintPrintingPhase)
    {
        // Report the change of a printing phase
        var phase = ""
        
        switch jobPhase
        {
        case LWPrintPrintingPhase.PrintingPhasePrepare:
            phase = "PrintingPhasePrepare"
        case LWPrintPrintingPhase.PrintingPhaseProcessing:
            phase = "PrintingPhaseProcessing"
        case LWPrintPrintingPhase.PrintingPhaseWaitingForPrint:
            phase = "PrintingPhaseWaitingForPrint"
        case LWPrintPrintingPhase.PrintingPhaseComplete:
            phase = "PrintingPhaseComplete"
           _ = self.viewController.navigationController?.popViewController(animated: false)
            //self.printComplete(connectionStatus: LWPrintConnectionStatus.ConnectionStatusNoError, deviceStatus: LWPrintStatusError.StatusErrorNoError, isSuspend: false)
        @unknown default:
            break
        }
        
        print("<\(#function)>phase=\(phase)")
    }
    
    func lwPrint(_ lwPrint: LWPrint!, didAbortPrintOperation errorStatus: LWPrintConnectionStatus, deviceStatus: LWPrintStatusError)
    {
        // It is called when undergoing a transition to the printing cancel operation due to a printing error
        self.printComplete(connectionStatus: errorStatus, deviceStatus: deviceStatus, isSuspend: false)
        
        let message = String(format: Util.getString("Error Status : %d\nDevice Status : %02X"), errorStatus.rawValue, deviceStatus.rawValue)
        Util.GeneralAlert(viewController: self.viewController, message: message)
    }
    
    func lwPrint(_ lwPrint: LWPrint!, didSuspendPrintOperation errorStatus: LWPrintConnectionStatus, deviceStatus: LWPrintStatusError)
    {
        // It is called when undergoing a transition to the printing restart operation due to a printing error
        self.printComplete(connectionStatus: errorStatus, deviceStatus: deviceStatus, isSuspend: true)
        
        let message = String(format: Util.getString("Error Status : %d\nDevice Status : %02X"), errorStatus.rawValue, deviceStatus.rawValue)
        Util.AlertRetryAction(viewController: self.viewController, title: Util.getString("Print failed"), message: message, actionOnRetry: self.lwPrint.resumeOfPrint, actionOnCancel: self.lwPrint.cancel)
    }

    private func performPrint()
    {
        guard let printerInfo = self.printerInfo else
        {
            return
        }
        
        DispatchQueue.global().async {
            
            // Set printing information
            self.lwPrint.setPrinterInformation(printerInfo)
            
            // Obtain printing status
            guard let lwStatus = self.lwPrint.fetchPrinterStatus() else
            {
                DispatchQueue.main.async {
                    let message = String(format: Util.getString("Can't get printer status."))
                    Util.GeneralAlert(viewController: self.viewController, message: message)
                }
                return
            }
            
            DispatchQueue.main.async {
                
                let dataProvider = self.dataProvider!
                
                // Make a print parameter
                let tapeWidth = self.lwPrint.tapeWidth(fromStatus: lwStatus)
                self.lwPrint.delegate = self
                
                let printParameter: [String: AnyObject] = [
                    LWPrintParameterKeyCopies: 1 as AnyObject,                                           // Number of copies(1 ... 99)
                    LWPrintParameterKeyTapeCut: LWPrintTapeCut.TapeCutEachLabel.rawValue as AnyObject,   // Tape cut method(LWPrintTapeCut)
                    LWPrintParameterKeyHalfCut: true as AnyObject,                                       // Set half cut (true:half cut on)
                    LWPrintParameterKeyPrintSpeed: false as AnyObject,                                   // Low speed print setting (true:low speed print on)
                    LWPrintParameterKeyDensity: 0 as AnyObject,                                          // Print density(-5 ... 5)
                    LWPrintParameterKeyTapeWidth: tapeWidth.rawValue as AnyObject,                       // Tape width(LWPrintTapeWidth)
                ]
                
                // Carry out printing
                self.lwPrint.do(dataProvider, printParameter: printParameter)
            }
        }
    }

    
    
    private func printComplete(connectionStatus: LWPrintConnectionStatus, deviceStatus: LWPrintStatusError, isSuspend: Bool){
        var msg = ""
        if connectionStatus == LWPrintConnectionStatus.ConnectionStatusNoError && deviceStatus == LWPrintStatusError.StatusErrorNoError{
            msg = "Print Complete."
        }
        else{
            if isSuspend{
                msg = String(format: "Print Error Re-Print [%02x].", deviceStatus.rawValue)
            }
            else{
                msg = String(format: "Print Error [%02x].", deviceStatus.rawValue)
            }
        }
        print(msg)
    }
}

class LWWorkOrderDataProvider: LWPrintDataProvider{
    
    var workOrder: WorkOrder!
    private var formDataString: [String: AnyObject]?
    
    init (workOrder: WorkOrder) {
        self.workOrder = workOrder
        
        if let _formPath = Bundle.main.path(forResource: "WorkOrderLabel", ofType: "plist")
        {
            formDataString = NSDictionary(contentsOfFile: _formPath) as? [String: AnyObject]
        }
    }
    
    override func startOfPrint()
    {
        // It is called only once when printing started
        print("<\(#function)>")
    }
    
    override func endOfPrint()
    {
        // It is called only once when printing finished
        print("<\(#function)>")
    }
    
    override func startPage()
    {
        // It is called when starting a page
        print("<\(#function)>")
    }
    
    override func endPage()
    {
        // It is called when finishing a page
        print("<\(#function)>")
    }
    
    override func numberOfPages() -> Int
    {
        // Return all pages printed
        print("<\(#function)>")
        return 1
    }
    
    override func formData(forPage pageIndex: Int) -> [AnyHashable : Any]! {
        // Return the form data for pageIndex page
        print("<\(#function)>pageIndex=\(pageIndex)")
        
        return formDataString
    }
    
    override func contentData(_ contentName: String!, forPage pageIndex: Int) -> Any! {
        // Return the data for the contentName of the pageIndex page
        print("<\(#function)>contentName=\(String(describing: contentName)),pageIndex=\(pageIndex)")
        if(contentName == "Barcode"){
            print(self.workOrder.Barcode!)
            return self.workOrder.Barcode!
        }
        else if(contentName == "OrderNumber"){
            print(self.workOrder.OrderNumber)
            return "WO  \(self.workOrder.OrderNumber)"
        }
        else if(contentName == "ContactName"){
            print("\(self.workOrder.contact.FirstName) \(self.workOrder.contact.LastName)")
            return "\(self.workOrder.contact.FirstName) \(self.workOrder.contact.LastName)"
        }
        return nil
    }
    
}
