//
/* NOTICE: All information contained herein is, and remains the property of Brightinsight Inc. or its customer. 
The intellectual and technical concepts contained herein are proprietary to Brightinsight Inc. or its customer and may be covered by U.S. and Foreign Patents, patents in process, and are protected by trade secret or copyright law.
Dissemination of this information or reproduction of this material is strictly forbidden unless prior written permission is obtained from Brightinsight Inc. or its customer. Access to the source code contained herein is hereby forbidden to anyone except current Brightinsight Inc. employees, managers or contractors who have executed
Confidentiality and Non-disclosure agreements explicitly covering such access.
*/
/**
* System Name : BISDKCore
* Component ID : BISDKCoreAPI
* Description : 
* Author: Vitor Cesco
* Copyright © : Brightinsight, Inc.
* -----------------------
* Revision Change
* -----------------------
* Author            Date             Version       Change-Description
*========================================================================================================
*/

import Foundation

class BISDKCoreAPI {
    var userCookie: String = ""
    var locationCode: String = ""
        
    private var config: BISDKConfig
    private var apiBuilder: BISDKApiBuilder

    init(_ config: BISDKConfig) {
        self.config = config
        self.apiBuilder = BISDKApiBuilder(config)
    }
    
    func authenticate(username: String, password: String, organizationId: String, completion: @escaping (BISDKLoginResponse?, String?, Int) -> ()) {
        let builder : BISDKApiRequest<BISDKLoginResponse> = apiBuilder.builder()
        print(" builder authenticate username \(username) pass: \(password)");
        let task = builder.withMethod("POST")
            .addHeaders([
                .custom("X-Username") : username,
                .custom("X-Password") : password,
                .custom("X-Organization") : organizationId
            ])
            .addPath("/authentication-service/authenticate")
            .build { (data, response, error) in
                guard
                    let url = response?.url,
                    let httpResponse = response as? HTTPURLResponse,
                    let fields = httpResponse.allHeaderFields as? [String: String]
                else {
                    completion(nil,"invalid data", defaultStatusCode)
                    return
                }
                let statusCode = httpResponse.statusCode
                let cookies = HTTPCookie.cookies(withResponseHeaderFields: fields, for: url)
                let cookieName = cookies.first?.name
                let cookieValue = cookies.first?.value
                                
                if cookieName != nil {
                    self.userCookie = cookieName!
                    self.userCookie.append("=\(String(cookieValue!.split(separator: ";")[0]))")
                }
                guard let data = data else {
                    completion(nil,"invalid data", statusCode)
                    return
                }
                guard let decodedData = try? JSONDecoder().decode(BISDKLoginResponse.self, from: data) else {
                    completion(nil,"failed to decode into \(BISDKLoginResponse.self)\n\(String(data: data, encoding: .utf8)!)", statusCode)
                    return
                }
                
                completion(decodedData, nil, statusCode)
            }
        task.resume()
    }
    
    func authorize(userCookie: String,
                   redirectUri: String,
                   clientId: String,
                   scope: String,
                   responseType: String,
                   state: String,
                   csrf: String,
                   decision: String,
                   codeChallenge: String,
                   codeChallengeMethod: String,
                   nonce: String,
                   completion: @escaping (String?, Int) -> ()) {
        let builder : BISDKApiRequest<BISDKToken> = apiBuilder.builder()
        print("run builder authorize")
        let task = builder.withMethod("POST")
            .addHeaders([.contentType: "application/x-www-form-urlencoded"])
            .addParameters(
                [
                    "Cookie": userCookie,
                    "redirect_uri": redirectUri,
                    "client_id": clientId,
                    "scope": scope,
                    "response_type": responseType,
                    "state": state,
                    "csrf": csrf,
                    "decision": decision,
                    "code_challenge": codeChallenge,
                    "code_challenge_method": codeChallengeMethod,
                    "nonce": nonce,
                    "apikey": config.apiKey
                ]
            )
            .addPath("/authentication-service/authorize")
            .buildAsFormURLEncodedNoRedirect { (data, response, error) in
                guard
                    let httpResponse = response as? HTTPURLResponse
                else {
                    completion("invalid data", defaultStatusCode)
                    return
                }
                let statusCode = httpResponse.statusCode
                
                if statusCode != 302 {
                    guard let data = data else {
                        completion("invalid data", statusCode)
                        return
                    }
                    guard let decodedData = try? JSONDecoder().decode(BISDKLoginResponse.self, from: data) else {
                        completion("failed to decode into \(BISDKLoginResponse.self)\n\(String(data: data, encoding: .utf8)!)", statusCode)
                        return
                    }
                    completion(decodedData.issues?.first?.details, statusCode)
                    return
                }
                
                guard
                    let location = httpResponse.allHeaderFields["Location"] as? String,
                    let url = URLComponents(string: location)
                else {
                    completion("Invalid location code", statusCode)
                    return
                }
                self.locationCode = url.queryItems?.first(where: { $0.name == "code" })?.value ?? ""

                completion(self.locationCode, statusCode)
            }
        task.resume()
    }
    
    func accessToken(userCookie: String,
                     code: String,
                     grantType: String,
                     clientId: String,
                     redirectUri: String,
                     codeVerifier: String,
                     completion: @escaping (BISDKToken?, String?, Int) -> ()) {
        let builder : BISDKApiRequest<BISDKToken> = apiBuilder.builder()
        let task = builder.withMethod("POST")
            .addHeaders([.contentType: "application/x-www-form-urlencoded"])
            .addParameters([
                "Cookie": userCookie,
                "code": code,
                "grant_type": grantType,
                "client_id": clientId,
                "redirect_uri": redirectUri,
                "code_verifier": codeVerifier,
                "apikey": config.apiKey
            ])
            .addPath("/authentication-service/access_token")
            .buildAsFormURLEncoded { (data, response, error) in
                let statusCode: Int = (response as? HTTPURLResponse)?.statusCode ?? defaultStatusCode
                
                guard let data = data else {
                    completion(nil, "invalid data", statusCode)
                    return
                }
                guard let decodedData = try? JSONDecoder().decode(BISDKToken.self, from: data) else {
                    completion(nil,"failed to decode into \(BISDKToken.self)\n\(String(data: data, encoding: .utf8)!)", statusCode)
                    return
                }
                
                completion(decodedData, nil, statusCode)
            }
        task.resume()
    }
    
    func refreshToken(grantType: String,
                      clientId: String,
                      redirectUri: String,
                      refreshToken: String,
                      codeVerifier: String,
                      completion: @escaping (BISDKToken?, String?, Int) -> ()) {
        let builder : BISDKApiRequest<BISDKToken> = apiBuilder.builder()
        let task = builder.withMethod("POST")
            .addHeaders([.contentType: "application/x-www-form-urlencoded"])
            .addParameters([
                "grant_type": grantType,
                "client_id": clientId,
                "redirect_uri": redirectUri,
                "refresh_token": refreshToken,
                "code_verifier": codeVerifier,
                "apikey": config.apiKey
            ])
            .addPath("/authentication-service/access_token")
            .buildAsFormURLEncoded { (data, response, error) in
                let statusCode: Int = (response as? HTTPURLResponse)?.statusCode ?? defaultStatusCode
                
                guard let data = data else {
                    completion(nil,"invalid data", statusCode)
                    return
                }
                guard let decodedData = try? JSONDecoder().decode(BISDKToken.self, from: data) else {
                    completion(nil,"failed to decode into \(BISDKToken.self)\n\(String(data: data, encoding: .utf8)!)",  statusCode)
                    return
                }
                
                completion(decodedData, nil, statusCode)
            }
        task.resume()
    }
    
    func logOut(accessToken: String, tokenId: String, completion: @escaping (Bool?, String?, Int) -> ()) {
        let builder : BISDKApiRequest<BISDKLoginResponse> = apiBuilder.builder()
        let task = builder.withMethod("POST")
            .withBody(["token":accessToken, "client_id":"oidc_pkce"])
            .addHeaders([.custom("iPlanetDirectoryPro"):tokenId])
            .addPath("/authentication-service/token/revoke")
            .build { (data, response, error) in
                guard let httpResponse = response as? HTTPURLResponse else {
                    completion(nil,"invalid response", defaultStatusCode)
                    return
                }
                let statusCode = httpResponse.statusCode
                completion(statusCode == 200, error?.localizedDescription, statusCode)
            }
        task.resume()
    }
}

fileprivate var defaultStatusCode: Int = -1
