//
//  EbayWebServiceManager.swift
//  Vendoo
//
//  Created by Okechi Onyeje on 6/3/16.
//  Copyright © 2016 Okechi Onyeje. All rights reserved.
//

import Foundation
import Locksmith

protocol EbayWebServiceManagerDelegate {
    func signInUser(string: String!)
}

class EbayWebServiceManager: NSObject {
    


    //API Manager class variables
    //----------------------------------------------//
    let baseURL = "https://api.sandbox.ebay.com/ws/api.dll"
    
    private var apiKey: String!
    private var devKey: String!
    private var certID: String!
    private var mutableData: NSMutableData = NSMutableData()
    private var currentElementName:NSString = ""
    private var userEmail:String = (NSUserDefaults.standardUserDefaults().objectForKey("email") as? String)!
    private var signinURL: String!
    private var xmlResponseDictionary: Dictionary<String, AnyObject!> = Dictionary<String, AnyObject!>()
    var delegate: EbayWebServiceManagerDelegate?
    var isAuthorized: Bool = NSUserDefaults.standardUserDefaults().boolForKey("ebayAuthorized")
    static var settingsDictionary = Dictionary<String , AnyObject>()
    //let tradingClient = EBayTradingServiceClient.sharedClient()
    //---------------------------------------------//
    //let tradingClient = SOAPEngine()
    
    
    override init(){
        super.init()
      //  self.tradingClient.debug = true
        if let path = NSBundle.mainBundle().pathForResource("Services", ofType: "plist"), dict = NSDictionary(contentsOfFile: path) as? [String: AnyObject] {
            
            self.apiKey = ((dict["Ebay"] as! Dictionary<String, AnyObject>)["consumerKey"] as! String)
            self.devKey = ((dict["Ebay"] as! Dictionary<String, AnyObject>)["devID"] as! String)
            self.certID = ((dict["Ebay"] as! Dictionary<String, AnyObject>)["CertID"] as! String)
            self.signinURL = ((dict["Ebay"] as! Dictionary<String, AnyObject>)["signin"] as! String)
            
            if(self.isAuthorized){
                let dictionary = Locksmith.loadDataForUserAccount(self.userEmail, inService: "vendoo_oauth_ebay")
                self.xmlResponseDictionary["eBayAuthToken"] = dictionary?["ebay_oauth"] as? String
                
            }
            //set default posting settings for ebay
            if(NSUserDefaults.standardUserDefaults().boolForKey("ebayDefaultsOverriden")) {
                
                EbayWebServiceManager.settingsDictionary = (NSUserDefaults.standardUserDefaults().objectForKey("ebaySettings") as? Dictionary<String, AnyObject>)!
            }
            else{
            
                EbayWebServiceManager.settingsDictionary = ([
                    "listingType":"FixedPriceItem",
                    "condition":"1500",
                    "listingDuration":"Days_7",
                    "ebaySite":"US",
                    "currency":"USD",
                    "shipping": [
                        "shippingType": "Flat",
                        "freeShipping": "true",
                        "shippingServicePriority": "1",
                        "shippingService":"UPSGround",
                        "shippingServiceAdditionalCost":"0.00"
                    ],
                    "payment":"PayPal",
                    "return":"ReturnsNotAccepted",
                    "postalCode":"00000"
                    
                    ] as Dictionary<String, AnyObject>)
                
                NSUserDefaults.standardUserDefaults().setObject(EbayWebServiceManager.settingsDictionary, forKey: "ebaySettings")
                
                NSUserDefaults.standardUserDefaults().setBool(true, forKey: "ebayDefaultsOverriden")
            }
        
        }
        
    }
    
    func reinit() {
    
        EbayWebServiceManager.settingsDictionary = (NSUserDefaults.standardUserDefaults().objectForKey("ebaySettings") as? Dictionary<String, AnyObject>)!
    }
    
}


//MARK: - authentication methods
extension EbayWebServiceManager {
    
    private func requestMaker(soapMessage: String!, theRequest: NSMutableURLRequest!) {
        let msgLength = soapMessage.characters.count
        theRequest.addValue("text/xml", forHTTPHeaderField: "Content-Type")
        theRequest.addValue(String(msgLength), forHTTPHeaderField: "Content-Length")
        theRequest.addValue("967", forHTTPHeaderField: "X-EBAY-API-COMPATIBILITY-LEVEL")
        theRequest.addValue(self.devKey, forHTTPHeaderField: "X-EBAY-API-DEV-NAME")
        theRequest.addValue(self.certID, forHTTPHeaderField: "X-EBAY-API-CERT-NAME")
        theRequest.addValue(self.apiKey, forHTTPHeaderField: "X-EBAY-API-APP-NAME")
        theRequest.addValue("0", forHTTPHeaderField: "X-EBAY-API-SITEID")
        theRequest.addValue("", forHTTPHeaderField: "SOAPAction")
        theRequest.HTTPMethod = "POST"
        theRequest.HTTPBody = soapMessage.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) // or false
        let connection = NSURLConnection(request: theRequest, delegate: self, startImmediately: true)
        connection!.start()
        
        if (connection == true) {
            var mutableData : Void = NSMutableData.initialize()
        }
    }

    func authorizeApp(){
        
        let soapMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
            "<GetSessionIDRequest xmlns=\"urn:ebay:apis:eBLBaseComponents\">" +
            "<RuName>Kroleo-Kroleo-Vendoo-S-ktqeobkk</RuName>" +
        "</GetSessionIDRequest>"
        
        let url = NSURL(string: self.baseURL)
        let theRequest = NSMutableURLRequest(URL: url!)
        theRequest.addValue("GetSessionID", forHTTPHeaderField: "X-EBAY-API-CALL-NAME")

        self.requestMaker(soapMessage, theRequest: theRequest)
        

    }
    
    func deauthorizeApp(){
        let soapMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
            "<RevokeTokenRequest xmlns=\"urn:ebay:apis:eBLBaseComponents\">" +
            "<RequesterCredentials>" +
            "<eBayAuthToken>\(self.xmlResponseDictionary["eBayAuthToken"])</eBayAuthToken>" +
        "</RequesterCredentials></RevokeTokenRequest>​"
        
        let url = NSURL(string: self.baseURL)
        let theRequest = NSMutableURLRequest(URL: url!)
        theRequest.addValue("RevokeToken", forHTTPHeaderField: "X-EBAY-API-CALL-NAME")
        
        self.requestMaker(soapMessage, theRequest: theRequest)
        
        //delete token from locksmith keychain
        do{
            try Locksmith.deleteDataForUserAccount(self.userEmail, inService: "vendoo_oauth_ebay")
            print("account credentials deleted for ebay")
            NSUserDefaults.standardUserDefaults().setBool(false, forKey: "ebayAuthorized")
            self.isAuthorized = false
            
        }
        catch{
            (error)
            print(error)
            //could not save data to keychain
            print("account credentials could not be deleted")
            
        }
    }
    
    func listItem(){
        
    }
    
    func fetchToken() {
        let soapMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
        "<FetchTokenRequest xmlns=\"urn:ebay:apis:eBLBaseComponents\"><SessionID>\(self.xmlResponseDictionary["SessionID"] as! String!)</SessionID></FetchTokenRequest>"
        
        let url = NSURL(string: self.baseURL)
        let theRequest = NSMutableURLRequest(URL: url!)
        theRequest.addValue("FetchToken", forHTTPHeaderField: "X-EBAY-API-CALL-NAME")

        self.requestMaker(soapMessage, theRequest: theRequest)
    }
}

extension EbayWebServiceManager: NSURLConnectionDelegate {
    
    func connection(connection: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
        mutableData.length = 0;
        print(response)
    }
    
    func connection(connection: NSURLConnection!, didReceiveData data: NSData!) {
        mutableData.appendData(data)
        print(data)
    }
    
    func connectionDidFinishLoading(connection: NSURLConnection!) {
        let response = NSString(data: mutableData, encoding: NSUTF8StringEncoding)
        
        print(response)
        let xmlParser = NSXMLParser(data: mutableData)
        xmlParser.delegate = self
        xmlParser.parse()
        xmlParser.shouldResolveExternalEntities = true
    }

    func connection(connection: NSURLConnection, willSendRequestForAuthenticationChallenge challenge: NSURLAuthenticationChallenge) {
        
        challenge.sender!.performDefaultHandlingForAuthenticationChallenge!(challenge)
        
    }
}

extension EbayWebServiceManager: NSXMLParserDelegate {
    
    func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
        currentElementName = elementName
    }
    
    func parser(parser: NSXMLParser, foundCharacters string: String) {
        switch (self.currentElementName) {
        case "SessionID":
            self.xmlResponseDictionary["SessionID"] = string
            var str = "\(signinURL)&SessID=\(string)"
            self.signinURL = str
            print(self.signinURL)
            print((self.currentElementName as String) + " : " + string)
            self.delegate?.signInUser(self.signinURL)
            break
        case "eBayAuthToken":
            self.xmlResponseDictionary["eBayAuthToken"] = string
            print(string)
            
            //save token to locksmith keychain
            do{
                try Locksmith.saveData(["ebay_oauth" : string], forUserAccount: self.userEmail, inService: "vendoo_oauth_ebay")
                print("account credentials saved")
                NSUserDefaults.standardUserDefaults().setBool(true, forKey: "ebayAuthorized")
                self.isAuthorized = true
                
                //Test authentication
                let soapmessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                    "<GetUserRequest xmlns=\"urn:ebay:apis:eBLBaseComponents\">" +
                    "<RequesterCredentials><eBayAuthToken>\(string)</eBayAuthToken>" +
                "</RequesterCredentials></GetUserRequest>"
                
                /*
                 *<?xml version="1.0" encoding="utf-8"?>
                 <GetUserRequest xmlns="urn:ebay:apis:eBLBaseComponents">
                 <!-- Call-specific Input Fields -->
                 <IncludeFeatureEligibility> boolean </IncludeFeatureEligibility>
                 <ItemID> ItemIDType (string) </ItemID>
                 <UserID> string </UserID>
                 <!-- Standard Input Fields -->
                 <DetailLevel> DetailLevelCodeType </DetailLevel>
                 <!-- ... more DetailLevel values allowed here ... -->
                 <ErrorLanguage> string </ErrorLanguage>
                 <MessageID> string </MessageID>
                 <Version> string </Version>
                 <WarningLevel> WarningLevelCodeType </WarningLevel>
                 </GetUserRequest>
                 */
                
                let url = NSURL(string: self.baseURL)
                let theRequest = NSMutableURLRequest(URL: url!)
                theRequest.addValue("GetUser", forHTTPHeaderField: "X-EBAY-API-CALL-NAME")
                
                self.requestMaker(soapmessage, theRequest: theRequest)
                
            }
            catch{
                (error)
                print(error)
                //could not save data to keychain
                print("account credentials could not be saved")
                
            }
            
            break
        case "HardExpirationTime" :
            print(string)
            break
        case "UserID" :
            print(string)
            EbayWebServiceManager.settingsDictionary["userID"] = string
            NSUserDefaults.standardUserDefaults().setObject(EbayWebServiceManager.settingsDictionary, forKey: "ebaySettings")
            break
        default:
            //print(string)
            print("\(self.currentElementName):\(string)")
        }
        
    }
}
