//
//  Facade+NewLogin.swift
//  kt
//
//  Created by neox on 29.11.17.
//  Copyright © 2017 SimpleCode. All rights reserved.
//

import Foundation

import XCGLogger

class LoginConnectionDelegate: NSObject, NSURLConnectionDataDelegate {
    var onFinish: (() -> Void)!
    var onError: ((NSError) -> Void)!
    var onSuccess: (() -> Void)!
    static var randomToken: String = ""
    var login: String = ""
    var password: String = ""
    var loginType: Facade.LoginType!
    static var counter = 0
    
    override init() {
        
    }
    
    func connection(connection: NSURLConnection, didFailWithError error: NSError) {
        //    let error = NSError(domain: "kz.telecom", code: 0, userInfo: [
        //      NSLocalizedDescriptionKey: §"login.error.incorrect_login_or_password",
        //      ])
        
        Router.globalLog.error(error.debugDescription)
        self.onError(error)
    }
    
    func connection(connection: NSURLConnection, didReceiveResponse response: NSURLResponse) {
        //print(response)
        print("-=-=-=-=-=-=-")
        Router.globalLog.debug(response)
        print("-=-=-=-=-=-=-")
        guard LoginConnectionDelegate.counter == 1 else { return }
        self.onFinish()
        
        if let responseUrl = response.URL where responseUrl.host == "www.google.kz" {
            let params = [
                Facade.LoginParamsKeys.ThirdStepClientId: LoginConnectionDelegate.randomToken
            ]
            let r = request(.POST, Facade.LoginUrls.ThirdStep, parameters: params, encoding: .JSON)
            let customDel = LoginConnectionDelegate()
            customDel.onError = onError
            customDel.onFinish = onFinish
            customDel.onSuccess = onSuccess
            customDel.login = login
            customDel.password = password
            customDel.loginType = loginType
            LoginConnectionDelegate.counter += 1
        
            print(r.cURLRepresentation())
        
            let con = NSURLConnection(request: r.request!, delegate: customDel)
            con!.start()
        } else {
            let error = NSError(domain: "kz.telecom", code: 0, userInfo: [
                NSLocalizedDescriptionKey: §"login.error.incorrect_login_or_password",
                ])
            self.onError(error)
        }
    }
    
    func connection(connection: NSURLConnection, didReceiveData data: NSData) {
        print(String(data: data, encoding: NSUTF8StringEncoding))

        switch LoginConnectionDelegate.counter {
        case 0:
            onFinish()
            
            let url = NSURL(string: Facade.LoginUrls.SecondStep)!
            
            var mutableRequest = NSMutableURLRequest(URL: url)
            mutableRequest.HTTPMethod = Method.GET.rawValue
            
            var params = Facade.LoginParams.SecondStep
            params[Facade.LoginParamsKeys.ClientIdKey] = LoginConnectionDelegate.randomToken
            
            mutableRequest = ParameterEncoding.URL.encode(mutableRequest, parameters: params).0
            
            var userParams = Facade.LoginParams.SecondStepBody
            userParams[Facade.LoginParamsKeys.BodyAuthType] = loginType.rawValue
            userParams[Facade.LoginParamsKeys.BodyUsername] = login
            userParams[Facade.LoginParamsKeys.BodyPassword] = password
            userParams[Facade.LoginParamsKeys.ClientIdKey] = LoginConnectionDelegate.randomToken
            
            print(userParams)
            
            mutableRequest.HTTPMethod = Method.POST.rawValue
            mutableRequest = ParameterEncoding.URL.encode(mutableRequest, parameters: userParams).0
            
            
            let r = request(mutableRequest)
            let customDel = LoginConnectionDelegate()
            customDel.onError = onError
            customDel.onFinish = onFinish
            customDel.onSuccess = onSuccess
            customDel.login = login
            customDel.password = password
            customDel.loginType = loginType
            
            LoginConnectionDelegate.counter += 1
            print(r.cURLRepresentation())
            
            let con = NSURLConnection(request: r.request!, delegate: customDel)
            con!.start()
            
            break
//        case 1:
//            self.onFinish()
//            let params = [
//                Facade.LoginParamsKeys.ThirdStepClientId: LoginConnectionDelegate.randomToken,
//                
//                Facade.LoginParamsKeys.ClientIdKey: LoginConnectionDelegate.randomToken
//                
//            ]
//            print(params)
//            let r = request(.POST, Facade.LoginUrls.ThirdStep, parameters: params, encoding: .JSON)
//            let customDel = LoginConnectionDelegate()
//            customDel.onError = onError
//            customDel.onFinish = onFinish
//            customDel.onSuccess = onSuccess
//            customDel.login = login
//            customDel.password = password
//            customDel.loginType = loginType
//            LoginConnectionDelegate.counter += 1
//            let con = NSURLConnection(request: r.request!, delegate: customDel)
//            con!.start()
//            
//            break
            
        case 2:
            self.onFinish()
            let json = JSON(data: data)
            print (json)
            if let errorCode = json["error_code"].int {
                // Success login
                if errorCode == 0 {
                    //                      let access_token = json["access_token"] as! String
                    //                      let client_id = randomToken
                    Facade.expiresIn = json["expires_in"].doubleValue
                    Facade.accessToken = json["access_token"].stringValue
                    Facade.clientId = LoginConnectionDelegate.randomToken
                    //											Facade.clientId = json["client_id"] as? String
                    //											self.notificationCenter.postNotificationName(FacadeLoginSuccess, object: self)
                    UserManager.sharedInstance().login = self.login
                    UserManager.sharedInstance().password = self.password
                    self.onSuccess()
                } else {
                    let error = NSError(domain: "kz.telecom", code: 0, userInfo: [
                        NSLocalizedDescriptionKey: json["error"].stringValue,
                        ])
                    self.onError(error)
                    //											self.notificationCenter.postNotificationName(FacadeLoginError, object: self, userInfo: [
                    //												FacadeNotificationErrorKey: error,
                    //											])
                }
            }
            
            // Error login or password
            
            //      CustomConnectionDelegate.counter += 1
            break
        default:
            break
        }
        
    }
    
    func connection(connection: NSURLConnection, canAuthenticateAgainstProtectionSpace protectionSpace: NSURLProtectionSpace) -> Bool {
        return protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust
    }
    
    func connection(connection: NSURLConnection, didReceiveAuthenticationChallenge challenge: NSURLAuthenticationChallenge) {
        if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
            //      if challenge.protectionSpace.host.containsString("cabinet.idport.kz") {
            challenge.sender?.useCredential(NSURLCredential(forTrust: challenge.protectionSpace.serverTrust!), forAuthenticationChallenge: challenge)
            
            challenge.sender?.continueWithoutCredentialForAuthenticationChallenge(challenge)
            //      }
        }
    }
}

extension Facade {
    
    func loginIdPort(login: String, password: String, loginType: LoginType, onSuccess: () -> Void, onError: (error: NSError) -> Void, onFinish: () -> Void) {
        LoginConnectionDelegate.counter = 0
                let cookiesStorage = NSHTTPCookieStorage.sharedHTTPCookieStorage()
        
                if let cookies = cookiesStorage.cookies where cookies.count != 0 {
                    for cookie in cookies {
                        if cookie.domain.rangeOfString("cabinet.idport.kz") != nil {
                            cookiesStorage.deleteCookie(cookie)
                        }
                    }
                }
        let uuid = NSUUID().UUIDString
        let randomToken = uuid.stringByReplacingOccurrencesOfString("-", withString: "")
        var params = LoginParams.FirstStep
        params[LoginParamsKeys.ClientIdKey] = randomToken
        
        //	First Step: Simple .GET
        let r = request(.GET, LoginUrls.FirstStep, parameters: params, encoding: .URL)
        let customDel = LoginConnectionDelegate()
        customDel.onError = onError
        customDel.onFinish = onFinish
        LoginConnectionDelegate.randomToken = randomToken
        customDel.onSuccess = onSuccess
        customDel.login = login
        customDel.password = password
        customDel.loginType = loginType
        
        print(r.cURLRepresentation())
        
        let con = NSURLConnection(request: r.request!, delegate: customDel)
        con!.start()
        
        Router.globalLog.debug("loginRequestStarted")
        
    }
}
