<commit_before>//
//  HTTPManager.swift
//  Bartleby
//
//  Created by <NAME> on 16/09/2015.
//  Copyright © 2015 https://pereira-da-silva.com for Chaosmos SAS
//  All rights reserved you can ask for a license.

import Foundation

#if !USE_EMBEDDED_MODULES
    import Alamofire
#endif

open class HTTPManager: NSObject {

    static open let SPACE_UID_KEY="spaceUID"


    static var baseURLApi: URL?

    static var userAgent: String {
        get {
            //@todo  implement cross anything user agent
            return "Bartleby\(Bartleby.versionString)/ (OS; Appversion; osVersion) (Apple; Mac)"
        }
    }

    fileprivate static var _hasBeenConfigured=false

    /**
     Configure the Manager
     */
    static open func configure()->() {
        if _hasBeenConfigured == false {
            let configuration = URLSessionConfiguration.default
            _ = SessionManager(configuration:configuration)
            _hasBeenConfigured=true
        }
    }


    // MARK: - Requests

    /**
     Returns a mutable request without a salted token.

     - parameter method: The Http Method
     - parameter url:    The URL

     - returns: the mutable request
     */
    static open func mutableRequestWithHeaders(_ method: String, url: URL) -> URLRequest {
        var request=URLRequest(url: url)
        request.httpMethod=method
        let headers=HTTPManager.baseHttpHeaders()
        for (k,v) in headers{
            request.addValue(v, forHTTPHeaderField: k)
        }
        return request
    }

    /**
     This method returns a mutable request with a salted token.

     - parameter documentUID:   the Document UID
     - parameter actionName: the action name e.g : CreateUser
     - parameter method:     the HTTP method
     - parameter url:        the url.

     - returns: the mutable
     */
    static open func requestWithToken(inDocumentWithUID documentUID: String, withActionName actionName: String, forMethod method: String, and url: URL) -> URLRequest {
        var request=URLRequest(url: url)
        request.httpMethod=method
        let headers=HTTPManager.httpHeadersWithToken(inDocumentWithUID:documentUID, withActionName: actionName)
        for (k,v) in headers{
            request.addValue(v, forHTTPHeaderField: k)
        }
        return request
    }

    // MARK: - HTTP Headers


    /**
     Returns the Http Headers

     - parameter documentUID:   the Document UID
     - parameter actionName: the actionName
     - parameter method:     the HTTP method (POST,GET, PATCH, DELETE, PUT)
     - parameter url:        the url.

     - returns: the http Headers
     */
    static open func httpHeadersWithToken(inDocumentWithUID documentUID: String, withActionName actionName: String)->[String:String]{
        var headers=HTTPManager.baseHttpHeaders()

        if let document=Bartleby.sharedInstance.getDocumentByUID(documentUID){

            // We prefer to Inject the token and spaceUID within the HTTP headers.
            // Note It is also possible to pass them as query strings.
            let tokenKey=HTTPManager.salt("\(actionName)#\(document.spaceUID)")
            let tokenValue=HTTPManager.salt(tokenKey)
            headers[tokenKey]=tokenValue

            // SpaceUID
            headers[HTTPManager.SPACE_UID_KEY]=document.spaceUID

            if document.metadata.identificationMethod == .key{
                if  let idv=document.metadata.identificationValue {
                    headers["kvid"]=idv
                }else{
                    headers["kvid"]=Default.VOID_STRING
                }
            }
            // We add the document observationUID
            headers["observationUID"]=document.UID

        }


        return headers
    }


    /**
     Returns a bunch of HTTP Header to be used in any Bartleby Http call
<commit_msg>HTTPmanager allow to setup an observation UID per request<commit_after>//
//  HTTPManager.swift
//  Bartleby
//
//  Created by <NAME> on 16/09/2015.
//  Copyright © 2015 https://pereira-da-silva.com for Chaosmos SAS
//  All rights reserved you can ask for a license.

import Foundation

#if !USE_EMBEDDED_MODULES
    import Alamofire
#endif

open class HTTPManager: NSObject {

    static open let SPACE_UID_KEY="spaceUID"
    static open let OBSERVATION_UID_KEY="observationUID"
    static open let KVID_KEY="kvid"


    static var baseURLApi: URL?

    static var userAgent: String {
        get {
            //@todo  implement cross anything user agent
            return "Bartleby\(Bartleby.versionString)/ (OS; Appversion; osVersion) (Apple; Mac)"
        }
    }

    fileprivate static var _hasBeenConfigured=false

    /**
     Configure the Manager
     */
    static open func configure()->() {
        if _hasBeenConfigured == false {
            let configuration = URLSessionConfiguration.default
            _ = SessionManager(configuration:configuration)
            _hasBeenConfigured=true
        }
    }


    // MARK: - Requests

    /**
     Returns a mutable request without a salted token.

     - parameter method: The Http Method
     - parameter url:    The URL

     - returns: the mutable request
     */
    static open func mutableRequestWithHeaders(_ method: String, url: URL) -> URLRequest {
        var request=URLRequest(url: url)
        request.httpMethod=method
        let headers=HTTPManager.baseHttpHeaders()
        for (k,v) in headers{
            request.addValue(v, forHTTPHeaderField: k)
        }
        return request
    }

    /**


     - parameter documentUID:   the Document UID
     - parameter actionName: the action name e.g : CreateUser
     - parameter method:     the HTTP method
     - parameter url:        the url.


     - returns: the mutable
     */


    ///  This method returns a mutable request with a salted token.
    ///
    /// - Parameters:
    ///   - documentUID: the document UID
    ///   - actionName: the action name
    ///   - method: the http Method
    ///   - url: the url
    ///   - oUID: an optional observationUID if not set we will use the document.UID
    /// - Returns: return value description
    static open func requestWithToken(inDocumentWithUID documentUID: String,
                                      withActionName actionName: String,
                                      forMethod method: String,
                                      and url: URL,
                                      observableBy oUID:String=Default.NO_UID) -> URLRequest {
        var request=URLRequest(url: url)
        request.httpMethod=method
        let headers=HTTPManager.httpHeadersWithToken(inDocumentWithUID:documentUID, withActionName: actionName)
        for (k,v) in headers{
            request.addValue(v, forHTTPHeaderField: k)
        }
        return request
    }

    // MARK: - HTTP Headers


    /**


     - parameter documentUID:   the Document UID
     - parameter actionName: the actionName
     - parameter method:     the HTTP method (POST,GET, PATCH, DELETE, PUT)
     - parameter url:        the url.

     - returns: the http Headers
     */


    ///  Returns the HTTP headers
    ///
    /// - Parameters:
    ///   - documentUID: the document UID (used to collect the spaceUID, the identification method, ...)
    ///   - actionName: the action Name (for token Permission level)
    ///   - oUID: an optional observationUID if not set we will use the document.UID
    /// - Returns: the HTTP headers
    static open func httpHeadersWithToken(inDocumentWithUID documentUID: String,
                                          withActionName actionName: String,
                                          observableBy oUID:String=Default.NO_UID)->[String:String]{
        var headers=HTTPManager.baseHttpHeaders()

        if let document=Bartleby.sharedInstance.getDocumentByUID(documentUID){

            // We prefer to Inject the token and spaceUID within the HTTP headers.
            // Note It is also possible to pass them as query strings.
            let tokenKey=HTTPManager.salt("\(actionName)#\(document.spaceUID)")
            let tokenValue=HTTPManager.salt(tokenKey)
            headers[tokenKey]=tokenValue

            // SpaceUID
            headers[HTTPManager.SPACE_UID_KEY]=document.spaceUID

            if document.metadata.identificationMethod == .key{
                if  let idv=document.metadata.identificationValue {
                    headers[HTTPManager.KVID_KEY]=idv
                }else{
                    headers[HTTPManager.KVID_KEY]=Default.VOID_STRING
                }
            }
            if oUID==Default.NO_UID{
                // We add the document observationUID
                headers[HTTPManager.OBSERVATION_UID_KEY]=document.UID
            }else{
                // We add the submitted observationUID
                headers[HTTPManager.OBSERVATION_UID_KEY]=oUID
            }
        }


        return headers
    }


    /**
     Returns a bunch of HTTP Header to be used in any Bartleby Http call

{'fraction_non_alphanumeric': 0.08012891753723049, 'fraction_numerical': 0.0026672593909757725, 'mean_word_length': 2.015750670241287, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 13, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 9, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2538641', 'n_tokens_mistral': 2438, 'n_tokens_neox': 2326, 'n_words': 702}