//
//  EpsonCustomerDisplayFiscal.swift
//  iPOS
//
//  Created by Zoran Albu on 7/27/18.
//  Copyright © 2018 BBC. All rights reserved.
//

import Foundation
import Foundation
import Foundation
import Alamofire

class EpsonCustomerDisplayFiscal: ICustomerDiplay {
    
    func decodedURL() -> String{
        if State.customerDisplayUrlString.contains("TCP:"){
            return State.customerDisplayUrlString.replacingOccurrences(of: "TCP:", with: "", options: .literal, range: nil)
        }
        return State.customerDisplayUrlString
    }
    
    func clearCustomerDisplay(){
        let clearDisplayXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
            + "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">"
            + "<s:Body>"
            + "<beginFiscalReceipt>"
            + "<displayText  operator=\"1\" data=\"\" />"
            + "<endFiscalReceipt  operator=\"1\" />"
            + "</s:Body>"
            + "</s:Envelope>"
        
        Alamofire.request(self.decodedURL(), method: .post, parameters: [:], encoding: clearDisplayXml, headers: Defaults.headers).response(completionHandler: { response in
        })
    }
    
    func showCustomerDisplay(item: ShoppingCartItem, isAdded: Bool){
        let clearDisplayXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
            + "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">"
            + "<s:Body>"
            + "<beginFiscalReceipt>"
            + "<displayText  operator=\"1\" data=\"\" />"
            + "<endFiscalReceipt  operator=\"1\" />"
            + "</s:Body>"
            + "</s:Envelope>"
        
        let firstLine = setCustomerDisplayFirstLine(name: item.barcodeInfo.Name, currency: settings.userSettings.currencyId, maxValueWidth: 5)
        
        Alamofire.request(self.decodedURL(), method: .post, parameters: [:], encoding: clearDisplayXml, headers: Defaults.headers).response(completionHandler: { response in
            
            if item.barcodeInfo.ProductId.isEmpty{
                return
            }
            
            var displayXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
                + "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">"
                + "<s:Body>"
                + "<beginFiscalReceipt>"
            
            var secondLine = ""
            if(!isAdded){
                secondLine = self.setCustomerDisplaySecondLine(itemValue: -item.NetRowValue/item.Quantity, totalValue: State.shoppingCart.netValue, maxValueWidth: 12)
            }
            else{
                secondLine = self.setCustomerDisplaySecondLine(itemValue: item.NetRowValue/item.Quantity, totalValue: State.shoppingCart.netValue, maxValueWidth: 12)
            }
            
            let msg = self.removeIllegalCharacters(message: firstLine)
            displayXml += "<displayText  operator=\"1\" data=\"\(msg)\(secondLine)\" />"
            displayXml += "<endFiscalReceipt  operator=\"1\" />"
                        + "</s:Body>"
                        + "</s:Envelope>"
            
            Alamofire.request(self.decodedURL(), method: .post, parameters: [:], encoding: displayXml, headers: Defaults.headers ).response(completionHandler: { response in
                
            })
        })
    }
    
    func setCustomerDisplayFirstLine(name: String, currency: String, maxValueWidth: Int) -> String {
        let lineWidth = 20
        let maxNameWidth = lineWidth - maxValueWidth - 1
        var name = name
        
        if name.count > maxNameWidth {
            let index = name.index(name.startIndex, offsetBy: maxNameWidth)
            name = String(name[..<index])
        }
        
        let spaceWidth = lineWidth - name.count - currency.count
        
        let result = name + String.init(repeating: " ", count: spaceWidth) + currency
        return result
    }
    
    func setCustomerDisplaySecondLine(itemValue: Double, totalValue: Double, maxValueWidth: Int) -> String {
        let lineWidth = 20
        let maxWidth = lineWidth - maxValueWidth - 1
        var itemValue = Util.DoubleToString(itemValue)
        let totalValue = Util.DoubleToString(totalValue)
        
        if itemValue.count > maxWidth {
            let index = itemValue.index(itemValue.startIndex, offsetBy: maxWidth)
            itemValue = String(itemValue[..<index])
        }
        
        let spaceWidth = lineWidth - itemValue.count - totalValue.count
        
        let result = itemValue + String.init(repeating: " ", count: spaceWidth) + totalValue
        return result
    }
    
    func removeIllegalCharacters(message: String) -> String{
        var msg = message
        msg = msg.replacingOccurrences(of: "&", with: "&amp;")
        msg = msg.replacingOccurrences(of: "<", with: "&lt;")
        msg = msg.replacingOccurrences(of: ">", with: "&gt;")
        msg = msg.replacingOccurrences(of: "\"", with: "&quot;")
        msg = msg.replacingOccurrences(of: "'", with: "&apos;")
        
        return msg
    }
    
    func showCustomerDisplay(line1: String, line2: String) {
        let clearDisplayXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
            + "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">"
            + "<s:Body>"
            + "<beginFiscalReceipt>"
            + "<displayText  operator=\"1\" data=\"\" />"
            + "<endFiscalReceipt  operator=\"1\" />"
            + "</s:Body>"
            + "</s:Envelope>"
        
        let firstLine = self.removeIllegalCharacters(message: line1)
        let secondLine = self.removeIllegalCharacters(message: line2)
        
        Alamofire.request(self.decodedURL(), method: .post, parameters: [:], encoding: clearDisplayXml, headers: Defaults.headers).response(completionHandler: { response in
            
            let l1 = setCustomerDisplayLine(name: firstLine)
            let l2 = setCustomerDisplayLine(name: secondLine)
            
            var displayXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
                + "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">"
                + "<s:Body>"
                + "<beginFiscalReceipt>"
            
            displayXml += "<displayText  operator=\"1\" data=\"\(l1)\(l2)\" />"
            displayXml += "<endFiscalReceipt  operator=\"1\" />"
                        + "</s:Body>"
                        + "</s:Envelope>"
            
            Alamofire.request(self.decodedURL(), method: .post, parameters: [:], encoding: displayXml, headers: Defaults.headers ).response(completionHandler: { response in
                
            })
        })
        
        func setCustomerDisplayLine(name: String) -> String {
            let lineWidth = 20
            let maxNameWidth = lineWidth
            var name = name
            
            if name.count > maxNameWidth {
                let index = name.index(name.startIndex, offsetBy: maxNameWidth)
                name = String(name[..<index])
            }
            
            let spaceWidth = lineWidth - name.count
            
            let result = name + String.init(repeating: " ", count: spaceWidth)
            return result
        }
    }
}
