//
//  CustomerDisplay.swift
//  iPOS
//
//  Created by bbc on 26/05/17.
//  Copyright © 2017 BBC. All rights reserved.
//

import Foundation
import Foundation
import Alamofire

class EpsonCustomerDisplayNonFiscal: 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 = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"><s:Body>"
            + "<epos-display xmlns=\"http://www.epson-pos.com/schemas/2012/09/epos-display\">"
            + "<clear/>"
            + "</epos-display>"
            + "</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 = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"><s:Body>"
            + "<epos-display xmlns=\"http://www.epson-pos.com/schemas/2012/09/epos-display\">"
            + "<clear/>"
            + "</epos-display>"
            + "</s:Body></s:Envelope>"
        
        let firstLine = setCustomerDisplayFirstLine(name: item.barcodeInfo.Name, currency: settings.userSettings.currencyId, maxValueWidth: 5)
        let msg = self.removeIllegalCharacters(message: firstLine)
        
        Alamofire.request(self.decodedURL(), method: .post, parameters: [:], encoding: clearDisplayXml, headers: Defaults.headers).response(completionHandler: { response in
            
            if item.barcodeInfo.ProductId.isEmpty{
                return
            }
            
            var displayXml = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"><s:Body>"
                + "<epos-display xmlns=\"http://www.epson-pos.com/schemas/2012/09/epos-display\">"
                + "<text>\(msg)</text>"
            
            if(!isAdded){
                let secondLine = self.setCustomerDisplaySecondLine(itemValue: -item.NetRowValue/item.Quantity, totalValue: State.shoppingCart.netValue, maxValueWidth: 12)
                displayXml += "<text>\(secondLine)</text>"
            }
            else{
                let secondLine = self.setCustomerDisplaySecondLine(itemValue: item.NetRowValue/item.Quantity, totalValue: State.shoppingCart.netValue, maxValueWidth: 12)
                displayXml += "<text>\(secondLine)</text>"
            }
            
            displayXml += "</epos-display>"
                + "</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 = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"><s:Body>"
            + "<epos-display xmlns=\"http://www.epson-pos.com/schemas/2012/09/epos-display\">"
            + "<clear/>"
            + "</epos-display>"
            + "</s:Body></s:Envelope>"
        
        let firstLine = self.setMessageOnLine(line: self.removeIllegalCharacters(message: line1))
        let secondLine = self.setMessageOnLine(line: self.removeIllegalCharacters(message: line2))
        
        Alamofire.request(self.decodedURL(), method: .post, parameters: [:], encoding: clearDisplayXml, headers: Defaults.headers).response(completionHandler: { response in
            
            var displayXml = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"><s:Body>"
                + "<epos-display xmlns=\"http://www.epson-pos.com/schemas/2012/09/epos-display\">"
                + "<text>\(firstLine)</text>"
            
            displayXml += "<text>\(secondLine)</text>"
            
            displayXml += "</epos-display>"
                + "</s:Body></s:Envelope>"
            
            Alamofire.request(self.decodedURL(), method: .post, parameters: [:], encoding: displayXml, headers: Defaults.headers ).response(completionHandler: { response in
                
            })
        })
    }
    
    func setMessageOnLine(line: String) -> String {
        let lineWidth = 20
        let maxNameWidth = lineWidth - 1
        var name = line

        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
    }
}
