//
//  DitronFiscalPrinter.swift
//  iPOS
//
//  Created by Zoran Albu on 3/15/18.
//  Copyright © 2018 BBC. All rights reserved.
//

import Foundation
import Alamofire

class TXTReceiptFiscalPrinter {
    var cmd: String
    
    init() {
        cmd = ""
    }
    
    func urlEncode(text: String) -> String{
        var text = text
        text = text.replacingOccurrences(of: " ", with: "+")
        text = text.replacingOccurrences(of: "=", with: "%3D")
        text = text.replacingOccurrences(of: ",", with: "%2C")
        text = text.replacingOccurrences(of: "\r\n", with: "%0d%0a")

        return text
    }
    
    func addLine(_ text: String) { cmd.append(text + "\r\n")}
    
    func beginFiscalReceipt(){
        //self.addLine("inp term = 178")
    }
    
    func beginNonFiscalReceipt(){
        self.addLine("NOFIS APRI")
    }
    
    func printNormal(message: String){
        let msg = removeIllegalCharacters(message: message)
        let noFisMessage = String.init(format: "NOFIS RIGA='%@'", msg)
        self.addLine(noFisMessage)
    }
    
    func printRecMessage(message: String){
        let msg = removeIllegalCharacters(message: message)
        let recMessage = String.init(format: "PRMSG RIGA='%@'", msg)
        self.addLine(recMessage)
    }
    
    func printRecFooter(footer: [String]){
        for line in footer{
            let msg = removeIllegalCharacters(message: line)
            let trailerMsg = String.init(format: "PRMSG RIGA='%@'", msg)
            self.addLine(trailerMsg)
        }
    }
    
    func printNonFiscalFooter(footer: [String]){
        for line in footer{
            let msg = removeIllegalCharacters(message: line)
            let trailerMsg = String.init(format: "NOFIS RIGA='%@'", msg)
            self.addLine(trailerMsg)
        }
    }
    
    func printNonFiscalHeader(header: [String]){
        for line in header{
            let msg = removeIllegalCharacters(message: line)
            let trailerMsg = String.init(format: "NOFIS RIGA='%@'", msg)
            self.addLine(trailerMsg)
        }
    }
    
    func printRecItem(description: String, quantity: Double, unitPrice: Double, department: Int){
        let desc = removeIllegalCharacters(message: description)
        
        let strQty: String = quantity == 1 ? "" : " QTY=\(quantity)" + ","
        let recItem =  String.init(format: "VEND REP=%d, PRE=%@,%@ DES='%@'", department, Util.DoubleToStringWithPointSeparator(unitPrice), strQty, desc)
        
        self.addLine(recItem)
    }
    
    func printRecItemAdjustment(amount: Double){
        let recItemAdjustment = String.init(format: "SCONTO VAL=%@", Util.DoubleToStringWithPointSeparator(amount))
        
        self.addLine(recItemAdjustment)
    }
    
    func printBarcode(barcode: String){
        let recBarcode = String.init(format: "ALLEG RIGA='%@', barcode=120", barcode)
        self.addLine(recBarcode)
    }
    
    func printNonFiscalBarcode(barcode: String){
        let noFisBarcode = String.init(format: "NOFIS RIGA='%@', barcode=120", barcode)
        self.addLine(noFisBarcode)
    }
    
    func printRecTotal(payments: [Payment]){
        for payment in payments{
            var ditronCategory: Int = 1
            
            switch payment.paymentType.CategoryCode {
            case PaymentCategory.CASH:
                ditronCategory = 1
                break
            case PaymentCategory.CHECK:
                ditronCategory = 3
                break
            case PaymentCategory.TICKET:
                ditronCategory = 4
                break
            case PaymentCategory.EFT:
                ditronCategory = 5
                break
            default:
                ditronCategory = 1
            }
            
            self.addLine("ALLEG ON")
            self.addLine(String.init(format: "CHIUS T=%d, IMP=%@", ditronCategory, Util.DoubleToStringWithPointSeparator(payment.amount)))
            
        }
    }
    
    func printCurrency(message:String){
        let msg = removeIllegalCharacters(message: message)
        let spaceWidth = Defaults.defaultPrinterColumns - msg.count
        let string = String.init(repeating: " ", count: spaceWidth) + msg
        let noFisCurrency = String.init(format: "NOFIS RIGA='%@'", string)
        self.addLine(noFisCurrency)
    }
    
    func displayText(description: String){
        
    }
    
    func endFiscalReceipt(){
        self.addLine("ALLEG FINE")
    }
    
    func endNonFiscalReceipt(){
        self.addLine("NOFIS CHIUDI")
    }
    
    func removeIllegalCharacters(message: String) -> String{
        var message = message
        message = message.replacingOccurrences(of: "\'", with: " ")
        message = message.replacingOccurrences(of: "\n", with: " ")
        message = message.replacingOccurrences(of: "\r", with: " ")
        
        return message
    }
}

class DitronFiscalPrinter: IPrinter{
    var ecrIpAddress = settings.FiscalPrinterUrl
    private let url = "http://%@%@"
    
    private let ecrWEC_init = "/ecrwec/init"
    private let ecrWEC_close = "/ecrwec/close"
    
    private let ecrWEC_cmd = "/ecrwec/cmd"
    private let ecrWEC_cmd_batch = "/ecrwec/cmd/batch"
    
    private let ecrWEC_cmd_body = "cmd=%@&async=%@"
    private let ecrWEC_cmd_batch_body = "file=%@&content=%@&async=%@"
    
    private let username = "admin"
    private let password = "admin"
    
    var headers: [String:String] = [:]
    
    private let FISCALEXPENSETYPE_AD: String = "AD"
    private let FISCALEXPENSETYPE_AA: String = "AA"
    
    init(){
        let credentialData = "\(username):\(password)".data(using: String.Encoding.utf8)!
        let base64Credentials = credentialData.base64EncodedString()
        self.headers = ["Authorization": "Basic \(base64Credentials)"]
    }
    
    public func getURL ( resource: String ) -> String {
        return String.init(format: url, ecrIpAddress, resource)
    }
    
    public func sendRequest(urlString: String, method: HTTPMethod, body: String?, wsCompletionHandler: @escaping (Bool?) -> Void) {
        Util.SetNetworkActivityIndicatorVisibilty(text: Util.getString("Please wait"), visible: true)
        let enconding: ParameterEncoding!
        if let body = body{
            enconding = body as ParameterEncoding
        }
        else{
            enconding = JSONEncoding.default
        }
        
        Alamofire.request(urlString, method: method, parameters: [:], encoding: enconding, headers: headers ).response(completionHandler: { response in
            var result: Bool? = nil
            if(response.response != nil){
                if (response.response!.statusCode < 300){
                    result = true
                }
                else {
                    result = false
                }
            }
            wsCompletionHandler(result)
            Util.SetNetworkActivityIndicatorVisibilty(text: nil, visible: false)
        })
    }
    
    public func sendRequestWithStringResponse(urlString: String, method: HTTPMethod, body: String?, wsCompletionHandler: @escaping (String?) -> Void) {
        Util.SetNetworkActivityIndicatorVisibilty(text: Util.getString("Please wait"), visible: true)
        let enconding: ParameterEncoding!
        if let body = body{
            enconding = body as ParameterEncoding
        }
        else{
            enconding = JSONEncoding.default
        }

        Alamofire.request(urlString, method: method, parameters: [:], encoding: enconding, headers: headers).responseString(completionHandler: { response in
            wsCompletionHandler(response.result.value)
            Util.SetNetworkActivityIndicatorVisibilty(text: nil, visible: false)
        })
    }
    
    func initWEC(completionHandler: @escaping(Bool?) -> Void){
        let urlString = getURL(resource: ecrWEC_init)
        self.sendRequest(urlString: urlString, method: .post, body: nil) { result in
            completionHandler(result)
        }
    }
    
    func closeWEC(completionHandler: @escaping(Bool?) -> Void){
        let urlString = getURL(resource: ecrWEC_close)
        self.sendRequest(urlString: urlString, method: .post, body: nil) { result in
            completionHandler(result)
        }
    }
    
    func printWorkOrder(_ workOrder: WorkOrder, completionHandler: @escaping (Bool?) -> Void){
        self.initWEC { initResult in
            guard let initResult = initResult else {
                //cannot connect to printer
                completionHandler(nil)
                return
            }
            
            if initResult == false{
                //the fiscal printer reported an error
                completionHandler(false)
                return
            }
        
            let rec = TXTReceiptFiscalPrinter()
            
            self.createNonFiscalCommandListFromWorkOrder(rec: rec, workOrder: workOrder)
            
            let urlString = self.getURL(resource: self.ecrWEC_cmd_batch)
            let encodedBody = rec.urlEncode(text: rec.cmd)
            let body = String.init(format: self.ecrWEC_cmd_batch_body, "batch.txt", encodedBody, "false")
            print(body)
            
            self.sendRequest(urlString: urlString, method: .post, body: body, wsCompletionHandler: { result in
                self.closeWEC(completionHandler: { closeResult in
                    completionHandler(result)
                })
            })
        }
    }
    
    func createNonFiscalCommandListFromWorkOrder(rec: TXTReceiptFiscalPrinter, workOrder: WorkOrder){
        rec.beginNonFiscalReceipt()
        
        rec.printNormal(message: "WorkOrder \(workOrder.OrderNumber)")
        rec.printNormal(message: "\(Util.DateToFullDateString(date: workOrder.CreateTime))")
        
        rec.printNormal(message: Util.getString("Client") + " \(workOrder.contact.FirstName) \(workOrder.contact.LastName)")
        
        if(workOrder.contact.FiscalCode != nil && workOrder.contact.FiscalCode != ""){
            rec.printNormal(message: Util.getString("Fiscal Code") + " \(workOrder.contact.FiscalCode!)")
        }
        rec.printNormal(message: "")
        rec.printCurrency(message: settings.userSettings.currencyId)
        for detail in workOrder.OrderDetail {
            if (detail.ParentOrderDetailId == nil) {
                rec.printNormal(message: "\(detail.ProductName!)  \(Util.DoubleToString(detail.OrderedQuantity)) x \(Util.DoubleToString(detail.GrossUnitValueVatIncluded))" )
                
                if let disc = detail.DiscountValue {
                    if (disc > 0) {
                        rec.printNormal(message: "  " + Util.getString("Discount") + "  \(Util.DoubleToString(disc))" )
                    }
                }
            }
            else {
                // print components as descriptions
                rec.printNormal(message: "  " + detail.ProductName!)
            }
        }
        rec.printNormal(message: Util.getString("TOTAL ORDER") + " \(Util.DoubleToString(workOrder.NetValueVatIncluded))")
        rec.printNormal(message: "")
        rec.printNonFiscalFooter(footer: settings.storeSetupSettings.footerLines)
        rec.printBarcode(barcode: workOrder.Barcode!)
        rec.printNormal(message: "")
        rec.endNonFiscalReceipt()
    }
    
    func printWorkOrderFiscal(_ workOrder: WorkOrder, parentId:String?, completionHandler: @escaping (Bool?) -> Void){
        self.initWEC { initResult in
            guard let initResult = initResult else {
                //cannot connect to printer
                completionHandler(nil)
                return
            }
            
            if initResult == false{
                //the fiscal printer reported an error
                completionHandler(false)
                return
            }
            
            let rec = TXTReceiptFiscalPrinter()
            
            self.createCommandListFromWorkOrder(rec: rec, workOrder: workOrder, parentId: parentId)
            
            let urlString = self.getURL(resource: self.ecrWEC_cmd_batch)
            let encodedBody = rec.urlEncode(text: rec.cmd)
            let body = String.init(format: self.ecrWEC_cmd_batch_body, "batch.txt", encodedBody, "false")
            print(body)
            
            self.sendRequest(urlString: urlString, method: .post, body: body, wsCompletionHandler: { result in
                self.closeWEC(completionHandler: { closeResult in
                    completionHandler(result)
                })
            })
        }
    }
    
    func createCommandListFromWorkOrder(rec: TXTReceiptFiscalPrinter, workOrder: WorkOrder, parentId: String?){
        var valueToPay:Double = 0.00
        
        rec.printRecMessage(message: Util.getString("Work Order") + " \(workOrder.OrderNumber)")
        
        rec.printRecMessage(message: Util.getString("Client") + " \(workOrder.contact.FirstName) \(workOrder.contact.LastName)")
        
        if parentId != nil{
            for detail in workOrder.OrderDetail {
                if let countryVat = getFiscalPrinterDepartment(vatId: detail.VatId){
                    detail.FiscalPrinterDepartment = countryVat
                }
                else{
                    break
                }
                
                if (detail.OrderDetailId == parentId) {
                    
                    var description = ""
                    if settings.storeSetupSettings.isOpticalClient && detail.MedicalDevice != nil && detail.MedicalDevice == true{
                        description = "(DM) "
                    }
                    if let productName = detail.ProductName{
                        description.append(productName)
                    }
                    
                    rec.printRecItem(description: description, quantity: detail.OrderedQuantity, unitPrice: detail.GrossUnitValueVatIncluded, department: detail.FiscalPrinterDepartment!)
                    
                    if let disc = detail.DiscountValue {
                        if (disc > 0) {
                            rec.printRecItemAdjustment( amount: disc)
                        }
                    }
                    
                    valueToPay += detail.GrossUnitValueVatIncluded
                    
                }
                else if detail.ParentOrderDetailId == parentId{
                    // print components as descriptions
                    var description = ""
                    if settings.storeSetupSettings.isOpticalClient && detail.MedicalDevice != nil && detail.MedicalDevice == true{
                        description = "(DM) "
                    }
                    if let productName = detail.ProductName{
                        description.append(productName)
                    }
                    
                    rec.printRecMessage(message: "  " + description)
                    
                    if let productCode = detail.ProductCode{
                        rec.printRecMessage(message: "  " + productCode)
                    }
                }
            }
        }
        
        rec.printBarcode(barcode: workOrder.Barcode!)
        
        rec.printRecTotal(payments: workOrder.payments)
        
        rec.printRecMessage(message: "")

        rec.printRecMessage(message: "Tk \(State.newTransactionNumber) POS Mobile \(State.cashRegister)")

        rec.printRecMessage(message: "")
        
        if(workOrder.contact.FiscalCode != nil && workOrder.contact.FiscalCode != ""){
            rec.printRecMessage(message: "************************************")
            rec.printRecMessage(message: Util.getString("PrintTicketFiscalCode"))
            rec.printRecMessage(message: "*********" + " \(workOrder.contact.FiscalCode!) " + "*********")
            
            rec.printRecMessage(message: "")
        }

        if settings.storeSetupSettings.isOpticalClient && workOrder.contact.FiscalCode != nil && workOrder.contact.FiscalCode != ""{
            let totalMedicalDevicesValue = calculateMedicalDeviceTotal(workOder: workOrder, parentId: parentId)
            if totalMedicalDevicesValue > 0 {
                addMedicalDeviceTotalsMessagesToList(rec: rec, totalMedicalDevicesValue: totalMedicalDevicesValue)
            }
        }
        
        rec.printRecFooter(footer: settings.storeSetupSettings.footerLines)
        
        rec.endFiscalReceipt()
    }
    
    private func calculateMedicalDeviceTotal(workOder: WorkOrder, parentId: String?) -> Double{
        var totalMedicalDevicesValue: Double = 0
        
        guard let parentId = parentId else{
            return 0
        }
        
        guard let orderDetail = workOder.getOrderDetailByKey(orderDetailId: parentId) else{
            return 0
        }
        
        let components = orderDetail.getComponentsForDetailByKey()
        if components.count > 0 {
            for component in components{
                if(component.FiscalExpenseType?.fiscalExpenseTypeId != nil && (component.FiscalExpenseType?.code == FISCALEXPENSETYPE_AD || component.FiscalExpenseType?.code == FISCALEXPENSETYPE_AA)){
                    totalMedicalDevicesValue += component.NetRowValueVatIncluded
                }
            }
        }
        else{
            if orderDetail.OrderDetailId == parentId{
                if(orderDetail.FiscalExpenseType?.fiscalExpenseTypeId != nil && (orderDetail.FiscalExpenseType?.code == FISCALEXPENSETYPE_AD || orderDetail.FiscalExpenseType?.code == FISCALEXPENSETYPE_AA)){
                    totalMedicalDevicesValue += orderDetail.NetRowValueVatIncluded
                }
            }
        }
        return totalMedicalDevicesValue
    }
    
    func getFiscalPrinterDepartment(vatId: Int?) -> Int?{
        if let countryVats = State.countryVats{
            for countryVat in countryVats{
                if countryVat.vatId == vatId{
                    return countryVat.fiscalPrinterDepartment
                }
            }
        }
        return nil
    }
    
    func printShoppingCart(_ cart: ShoppingCart, completionHandler: @escaping (Bool?) -> Void){
        self.initWEC { initResult in
            guard let initResult = initResult else {
                //cannot connect to printer
                completionHandler(nil)
                return
            }

            if initResult == false{
                //the fiscal printer reported an error
                completionHandler(false)
                return
            }

            let rec = TXTReceiptFiscalPrinter()
            self.createCommandListFromShoppingCart(rec: rec, cart:cart)
            
            let urlString = self.getURL(resource: self.ecrWEC_cmd_batch)
            let encodedBody = rec.urlEncode(text: rec.cmd)
            let body = String.init(format: self.ecrWEC_cmd_batch_body, "batch.txt", encodedBody, "false")
            print(body)
            
            self.sendRequest(urlString: urlString, method: .post, body: body, wsCompletionHandler: { result in
                self.closeWEC(completionHandler: { closeResult in
                    completionHandler(result)
                })
            })
        }
    }
    
    func createCommandListFromShoppingCart(rec: TXTReceiptFiscalPrinter, cart: ShoppingCart){
        for cartItem in cart.cartItems {
            var description = ""
            if settings.storeSetupSettings.isOpticalClient && cartItem.barcodeInfo.MedicalDevice != nil && cartItem.barcodeInfo.MedicalDevice == true{
                description = "(DM) "
            }
            description.append(cartItem.barcodeInfo.Name)
            rec.printRecItem(description: description, quantity: cartItem.Quantity, unitPrice: cartItem.GrossUnitValue, department: cartItem.barcodeInfo.FiscalPrinterDepartment!)
            
            if cartItem.DiscountValue > 0 {
                rec.printRecItemAdjustment(amount: cartItem.DiscountValue)
            }
            
            rec.printRecMessage(message: "  " + cartItem.barcodeInfo.Code)
        }
        
        rec.printRecTotal(payments: cart.payments)
        
        rec.printRecMessage(message: "")
        
        rec.printRecMessage(message: "Tk. \(State.newTransactionNumber) / POS Mobile \(State.cashRegister)")

        rec.printRecMessage(message: "")
        
        if(State.contactFiscalCodeForTransaction != nil && State.contactFiscalCodeForTransaction != "") {
            rec.printRecMessage(message: Util.getString("Fiscal Code") + " \((State.contactFiscalCodeForTransaction)!)")

            rec.printRecMessage(message: "")
        }

        if settings.storeSetupSettings.isOpticalClient && State.contactFiscalCodeForTransaction != nil && State.contactFiscalCodeForTransaction != ""{
            let totalMedicalDevicesValue = calculateMedicalDeviceTotal(cart: cart)
            addMedicalDeviceTotalsMessagesToList(rec: rec, totalMedicalDevicesValue: totalMedicalDevicesValue)
        }
        
        rec.printRecFooter(footer: settings.storeSetupSettings.footerLines)
        
        rec.printRecMessage(message: "")
        
        rec.printBarcode(barcode: State.transactionBarcode)
        
        rec.endFiscalReceipt()
    }
    
    private func calculateMedicalDeviceTotal(cart: ShoppingCart) -> Double{
        var totalMedicalDevicesValue: Double = 0
        for item in cart.cartItems{
            if (item.fiscalExpenseTypeId != nil && (item.fiscalExpenseTypeCode == FISCALEXPENSETYPE_AD || item.fiscalExpenseTypeCode == FISCALEXPENSETYPE_AA)){
                totalMedicalDevicesValue += item.NetRowValue
            }
        }
        return totalMedicalDevicesValue
    }
    
    private func addMedicalDeviceTotalsMessagesToList(rec: TXTReceiptFiscalPrinter, totalMedicalDevicesValue: Double) {
        if (totalMedicalDevicesValue != 0){
            rec.printRecMessage(message: "")
            rec.printRecMessage(message: "------------------------------")
            rec.printRecMessage(message: "(DM)=DISPOSITIVO MEDICO")
            rec.printRecMessage(message: "Prod. con marcatura CE")
            rec.printRecMessage(message: "dir. 93/42/CEE e ss.mm")
            rec.printRecMessage(message: "------------------------------")
            rec.printRecMessage(message: "Valore tot. detraibile nella")
            rec.printRecMessage(message: String.init(format: "dich. dei redditi: %@ %@", Util.DoubleToStringWithPointSeparator(totalMedicalDevicesValue), settings.userSettings.currencyId))
            rec.printRecMessage(message: "------------------------------")
        }
    }
    
    func printPaidAdvanceNonFiscal(_ workOrder: WorkOrder, completionHandler: @escaping (Bool?) -> Void){
        self.initWEC { initResult in
            guard let initResult = initResult else {
                //cannot connect to printer
                completionHandler(nil)
                return
            }
            
            if initResult == false{
                //the fiscal printer reported an error
                completionHandler(false)
                return
            }
            
            var actionSucceed = [Bool]()
            
            for copyNr in 1...2{
                let rec = TXTReceiptFiscalPrinter()
                rec.beginNonFiscalReceipt()
                rec.printNormal(message: Util.getString("ADVANCE NR.") + " \(State.newTransactionNumber)")
                rec.printNormal(message: "")
                let formatter = DateFormatter()
                formatter.dateFormat = "dd/MM/yyyy"
                rec.printNormal(message: Util.getString("Date") + ": \(formatter.string(from: workOrder.CreateTime))")
                rec.printNormal(message: Util.getString("Order") + ": \(workOrder.OrderNumber)")
                
                rec.printNormal(message: Util.getString("Client") + ": \(workOrder.contact.getFullName())")
                
                if let fiscalCode = workOrder.contact.FiscalCode{
                    rec.printNormal(message: Util.getString("PrintTicketFiscalCode") + ": \(fiscalCode)")
                }
                rec.printNormal(message: "")
                if let currency = workOrder.CurrencyId{
                    rec.printNormal(message: Util.getString("Advance value") + ": \(Util.DoubleToString(workOrder.AdvanceRequiredValue!))" + " \(currency)")
                    rec.printNormal(message: Util.getString("Total order") + ": \(Util.DoubleToString(workOrder.NetValueVatIncluded))" + " \(currency)")
                }
                else{
                    rec.printNormal(message: Util.getString("Advance value") + ": \(Util.DoubleToString(workOrder.AdvancePayedValue!))" + " \(settings.userSettings.currencyId)")
                    rec.printNormal(message: Util.getString("Total order") + ": \(Util.DoubleToString(workOrder.NetValueVatIncluded))" + " \(settings.userSettings.currencyId)")
                }
                rec.printNormal(message: "")
                if copyNr == 1{
                    rec.printNonFiscalFooter(footer: settings.storeSetupSettings.advanceMessageLines1)
                    rec.printNonFiscalFooter(footer: settings.storeSetupSettings.advanceMessageLines2)
                    rec.printNormal(message: "")
                    rec.printNormal(message: Util.getString("CustomerCopy"))
                }
                else{
                    rec.printNormal(message: Util.getString("StoreCopy"))
                }
                rec.endNonFiscalReceipt()
            
            
                let urlString = self.getURL(resource: self.ecrWEC_cmd_batch)
                let encodedBody = rec.urlEncode(text: rec.cmd)
                let body = String.init(format: self.ecrWEC_cmd_batch_body, "batch.txt", encodedBody, "false")
                print(body)
                
                self.sendRequest(urlString: urlString, method: .post, body: body, wsCompletionHandler: { result in
                    actionSucceed.append(false)
                    if result == true{
                       actionSucceed[actionSucceed.count - 1] = true
                    }
                    if(actionSucceed.count == 2){
                        if((actionSucceed[0] == true) && (actionSucceed[1]) == true){
                            self.closeWEC(completionHandler: { closeResult in
                                completionHandler(result)
                            })
                        }
                        else{
                            completionHandler(false)
                        }
                    }
                })
            }
        }
    }
    
    func printShoppingCartGiftReceipt(receipt: Receipt, movements: [Movement], receiptPayments: [ReceiptPayment], completionHandler: @escaping (Bool?) -> Void){
        self.initWEC { initResult in
            guard let initResult = initResult else {
                //cannot connect to printer
                completionHandler(nil)
                return
            }
            
            if initResult == false{
                //the fiscal printer reported an error
                completionHandler(false)
                return
            }
            
            let rec = TXTReceiptFiscalPrinter()
            self.createGiftReceiptCommandListFromShoppingCart(rec: rec, receipt: receipt, movements: movements, receiptPayments: receiptPayments)
            
            let urlString = self.getURL(resource: self.ecrWEC_cmd_batch)
            let encodedBody = rec.urlEncode(text: rec.cmd)
            let body = String.init(format: self.ecrWEC_cmd_batch_body, "batch.txt", encodedBody, "false")
            print(body)
            
            self.sendRequest(urlString: urlString, method: .post, body: body, wsCompletionHandler: { result in
                self.closeWEC(completionHandler: { closeResult in
                    completionHandler(result)
                })
            })
        }
    }
    
    private func createGiftReceiptCommandListFromShoppingCart(rec: TXTReceiptFiscalPrinter, receipt: Receipt, movements: [Movement], receiptPayments: [ReceiptPayment]){
        rec.beginNonFiscalReceipt()
        for movement in movements {
            if let barcode = movement.barcodeInfo.Barcode{
                rec.printNormal(message: barcode)
            }
            rec.printNormal(message: movement.barcodeInfo.Name)
            rec.printNormal(message: "")
        }
        
        rec.printNormal(message: "")
        rec.printNonFiscalFooter(footer: settings.storeSetupSettings.footerLines)
        rec.printNormal(message: "")
        rec.printNonFiscalBarcode(barcode: receipt.receiptBarcode!)
        rec.printNormal(message: "")
        rec.printNormal(message: "Tk. \(receipt.receiptNumber!) / POS Mobile \(receipt.cashRegister!)")
        rec.printNormal(message: Util.DateToFullDateString(date: receipt.createTime))
        rec.endNonFiscalReceipt()
    }
    
    func printIngenicoResponse(response: PTTransactionResult, completionHandler: @escaping (Bool?) -> Void){
        self.initWEC { initResult in
            guard let initResult = initResult else {
                //cannot connect to printer
                completionHandler(nil)
                return
            }
            
            if initResult == false{
                //the fiscal printer reported an error
                completionHandler(false)
                return
            }
            
            var actionSucceed: [Bool] = [Bool]()
            let ticketRows = response.ticket?.components(separatedBy: "\r\n")
            for copyNr in 1...2{
                let rec = TXTReceiptFiscalPrinter()
                rec.beginNonFiscalReceipt()
                rec.printNormal(message: "")
                if copyNr == 1{
                    rec.printNormal(message: Util.getString("***STORE COPY***"))
                }
                else{
                    rec.printNormal(message: Util.getString("***CLIENT COPY***"))
                }
                rec.printNormal(message: "")
                for row in ticketRows!{
                    rec.printNormal(message: row)
                }
                rec.printNormal(message: "")
                if copyNr == 1{
                    rec.printNormal(message: Util.getString("Customer signature"))
                    rec.printNormal(message: "")
                }
                rec.printNormal(message: "Tk \(State.newTransactionNumber) POS Mobile \(State.cashRegister)")
                rec.printNormal(message: Util.DateToFullDateString(date: Date()))
                rec.printNormal(message: "")
                rec.endNonFiscalReceipt()
            
                let urlString = self.getURL(resource: self.ecrWEC_cmd_batch)
                let encodedBody = rec.urlEncode(text: rec.cmd)
                let body = String.init(format: self.ecrWEC_cmd_batch_body, "batch.txt", encodedBody, "false")
                print(body)
                
                self.sendRequest(urlString: urlString, method: .post, body: body, wsCompletionHandler: { result in
                    actionSucceed.append(false)
                    if result == true{
                        actionSucceed[copyNr-1] = true
                    }
                    
                    if(actionSucceed.count == 2){
                        if((actionSucceed[0] == true) && (actionSucceed[1]) == true){
                            self.closeWEC(completionHandler: { closeResult in
                                completionHandler(result)
                            })
                        }
                        else{
                            completionHandler(false)
                        }
                    }
                })
            }
        }
    }
    
    func printIngenicoErrorResponse(response: PTTransactionResult, amount: Double, completionHandler: @escaping (Bool?) -> Void){
        self.initWEC { initResult in
            guard let initResult = initResult else {
                //cannot connect to printer
                completionHandler(nil)
                return
            }
            
            if initResult == false{
                //the fiscal printer reported an error
                completionHandler(false)
                return
            }
            
            let rec = TXTReceiptFiscalPrinter()
            rec.beginNonFiscalReceipt()
            rec.printNormal(message: "")
            rec.printNormal(message: "ACQUISTO")
            rec.printNormal(message: "DATA \(Util.DateToFullDateString(date: Date()))")
            rec.printNormal(message: "TML: \(settings.TerminalId)")
            rec.printNormal(message: "PAN: \(response.pan ?? "")")
            rec.printNormal(message: "SCAD. xx/xx/xx")
            rec.printNormal(message: "STAN: \(response.stan ?? "")")
            rec.printNormal(message: "")
            rec.printNormal(message: "\(settings.userSettings.currencyId) \(Util.DoubleToStringWithTwoDecimals(amount))")
            rec.printNormal(message: "")
            rec.printNormal(message: "************************")
            rec.printNormal(message: "\(response.transactionMessage ?? "")")
            rec.printNormal(message: "************************")
            rec.endNonFiscalReceipt()
            
            let urlString = self.getURL(resource: self.ecrWEC_cmd_batch)
            let encodedBody = rec.urlEncode(text: rec.cmd)
            let body = String.init(format: self.ecrWEC_cmd_batch_body, "batch.txt", encodedBody, "false")
            print(body)
            
            self.sendRequest(urlString: urlString, method: .post, body: body, wsCompletionHandler: { result in
                self.closeWEC(completionHandler: { closeResult in
                    completionHandler(result)
                })
            })
        }
    }
    
    func printZReport(completionHandler: @escaping (Bool?) -> Void){
        self.initWEC { initResult in
            guard let initResult = initResult else {
                //cannot connect to printer
                completionHandler(false)
                return
            }
            
            if initResult == false{
                //the fiscal printer reported an error
                completionHandler(false)
                return
            }
            
            let rec = TXTReceiptFiscalPrinter()
            
            let urlString = self.getURL(resource: self.ecrWEC_cmd)
            let body = "cmd=\(rec.urlEncode(text: "AZZGIO TIPO=1"))"
            self.sendRequest(urlString: urlString, method: .post, body: body, wsCompletionHandler: { result in
                self.closeWEC(completionHandler: { closeResult in
                    if result == nil || result == false{
                        completionHandler(false)
                    }
                    else{
                        completionHandler(true)
                    }
                })
            })
        }
    }
    
    func getTotalSalesForDepartment(department: Int, completionHandler: @escaping (Double) -> Void){
        completionHandler(0)
    }
    
    private func readTotals(completionHandler: @escaping (Bool?) -> Void){
        self.initWEC { initResult in
            guard let initResult = initResult else {
                //cannot connect to printer
                completionHandler(nil)
                return
            }
            
            if initResult == false{
                //the fiscal printer reported an error
                completionHandler(false)
                return
            }
            
            let rec = TXTReceiptFiscalPrinter()
            
            let urlString = self.getURL(resource: self.ecrWEC_cmd)
            let fileName = "WSDitron_Totals.txt"
            let body = "cmd=\(rec.urlEncode(text: "LEGGI NF=99, FILE='\(fileName)'"))"
            self.sendRequest(urlString: urlString, method: .post, body: body, wsCompletionHandler: { getTotalsResult in
                if getTotalsResult == true{
                    let urlString = self.getURL(resource: "/dwn/\(fileName)")
                    self.sendRequestWithStringResponse(urlString: urlString, method: .get, body: nil, wsCompletionHandler: { dwnResult in
                       
                    })
                }
                else{
                    self.closeWEC(completionHandler: { closeResult in
                        completionHandler(getTotalsResult)
                    })
                }
            })
        }
    }
    
    func testFiscalPrinter(completionHandler: @escaping (Bool?) -> Void){
        self.initWEC { initResult in
            guard let initResult = initResult else {
                completionHandler(nil)
                return
            }
            
            if initResult == false{
                completionHandler(false)
                return
            }
            
            self.closeWEC{ closeResult in
                completionHandler(closeResult)
            }
        }
    }
    
    func printVoucherMessageNonFiscal(voucherMessage: String, completionHandler: @escaping (Bool?) -> Void) {
        let rec = TXTReceiptFiscalPrinter()
        rec.beginNonFiscalReceipt()
        
        let messages = voucherMessage.components(separatedBy: "\n")
        for msg in messages{
            rec.printNormal(message: msg)
        }
        
        rec.endNonFiscalReceipt()
        
        print(rec)
       
        
        let urlString = self.getURL(resource: self.ecrWEC_cmd_batch)
        let encodedBody = rec.urlEncode(text: rec.cmd)
        let body = String.init(format: self.ecrWEC_cmd_batch_body, "batch.txt", encodedBody, "false")
        print(body)
        
        var succes = false
        self.sendRequest(urlString: urlString, method: .post, body: body, wsCompletionHandler: { result in
            self.closeWEC(completionHandler: { closeResult in
                if result == true{
                    succes = true
                }
                completionHandler(succes)
            })
        })
    }
    
    func isPrinterStateIdle(completionHandler: @escaping (Bool) -> Void) {
        completionHandler(true)
    }
    
    func printShoppingCartVoucherGift(_ cart: ShoppingCart, completionHandler: @escaping (Bool?) -> Void) {
        completionHandler(true)
    }
    
    func getFiscalPrinterSerialNumber(completionHandler: @escaping (String?) -> Void) {
        completionHandler(nil)
    }
    
    func printShoppingCartRefund(_ cart: ShoppingCart, completionHandler: @escaping (Bool?) -> Void) {
        completionHandler(true)
    }
    
    func reprintReceipt(xml: String, barcode: String, completionHandler: @escaping (Bool?) -> Void) {
        completionHandler(true)
    }
    
    func getFiscalPrinterFirmwareVersion(completionHandler: @escaping (String?) -> Void) {
        completionHandler(nil)
    }
}
