//
//  Login.swift
//  iPOS
//
//  Created by bbc on 09/11/2017.
//  Copyright © 2017 BBC. All rights reserved.
//

import Foundation
import Alamofire
import SWXMLHash

class LoginRequest {
    static let wsdlURL = "https://www.hoyailog.com/soap/order/v2?wsdl"
    static let countryCode = "it"
    static let maxCount = 0
    static let secKey = settings.storeSetupSettings.securityKey
    static let customerNumber = settings.storeSetupSettings.customerNumber
    static let loginName = settings.storeSetupSettings.loginName
    static let loginPassword = settings.storeSetupSettings.loginPassword
    static var sessionId = ""
    static let headers: HTTPHeaders = [
        "Content-Type" : "application/soap+xml"
    ]
    static let NEWLINE = "\n"
    
    static func createLoginXML() -> String{
        var xml = String()
        xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
            + NEWLINE    + "<env:Envelope xmlns:env=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:ns1=\"urn:SilentOrder\">"
            + NEWLINE    +      "<env:Body>"
            + NEWLINE    +          "<ns1:login>"
            + NEWLINE    +              "<secKey>\(secKey)</secKey>"
            + NEWLINE    +              "<countryCode>\(countryCode)</countryCode>"
            + NEWLINE    +              "<customerNumber>\(customerNumber)</customerNumber>"
            + NEWLINE    +              "<loginName>\(loginName)</loginName>"
            + NEWLINE    +              "<loginPassword>\(loginPassword)</loginPassword>"
            + NEWLINE    +          "</ns1:login>"
            + NEWLINE    +      "</env:Body>"
            + NEWLINE    +  "</env:Envelope>"
        
        return xml
    }
    
    static func login(completionHandler: @escaping([LensOrder]) -> Void){
        let xml = createLoginXML()
        
        Util.SetNetworkActivityIndicatorVisibilty(text: Util.getString("Loading")+"...", visible: true)
        
        Alamofire.request(wsdlURL, method: .post, parameters: [:], encoding: xml, headers: headers ).response { response in
            if let data = response.data{
               
                let xmlParse = SWXMLHash.parse(data)
                
                if let sessionIdent = xmlParse["env:Envelope"]["env:Body"]["ns1:loginResponse"]["sessionIdent"].element?.text {
                    sessionId = sessionIdent
                }
                
                getTrackAndTraceList(completionHandler: { lensOrder in
                    completionHandler(lensOrder)
                })
            }
            Util.SetNetworkActivityIndicatorVisibilty(text: nil, visible: false)
        }
    }
    
    static func createGetTrackAndTraceListXML() -> String{
        var xml = String()
        xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
            + NEWLINE    + "<env:Envelope xmlns:env=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:ns1=\"urn:SilentOrder\">"
            + NEWLINE        + "<env:Body>"
            + NEWLINE            + "<ns1:getTrackAndTraceList>"
            + NEWLINE                + "<secKey>\(secKey)</secKey>"
            + NEWLINE                + "<sessionIdent>\(sessionId)</sessionIdent>"
            + NEWLINE                + "<maxCount>\(maxCount)</maxCount>"
            + NEWLINE            + "</ns1:getTrackAndTraceList>"
            + NEWLINE        + "</env:Body>"
            + NEWLINE    + "</env:Envelope>"
        
        return xml
    }
    
    static func getTrackAndTraceList(completionHandler: @escaping([LensOrder]) -> Void) {
        let xml = createGetTrackAndTraceListXML()
        
        Util.SetNetworkActivityIndicatorVisibilty(text: Util.getString("Loading")+"...", visible: true)
        
        Alamofire.request(wsdlURL, method: .post, parameters: [:], encoding: xml, headers: headers ).response { response in
            if let data = response.data{

                let xmlParse = SWXMLHash.parse(data)
                
                var lensOrders: [LensOrder] = [LensOrder]()
                
                if let items = xmlParse["env:Envelope"]["env:Body"]["ns1:getTrackAndTraceListResponse"]["getTrackAndTraceListResult"]["list"].element?.children {
                    for child in items{
                        do{
                            let childXML = SWXMLHash.parse(child.description)
                            let lensOrder: LensOrder = try childXML["item"].value()
                            lensOrders.append(lensOrder)
                        }
                        catch{
                            
                        }
                    }
                }
                
                completionHandler(lensOrders)
            }
            Util.SetNetworkActivityIndicatorVisibilty(text: nil, visible: false)
        }
    }
}
