//
/* 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 : BISDKCoreModule
* Description : 
* Author: Vitor Cesco
* Copyright © : Brightinsight, Inc.
* -----------------------
* Revision Change
* -----------------------
 * Author                        Date             Version            Change-Description
 Arnold Dominguez       09/06/21            1.1                 Refactor for cross-platform design.
*========================================================================================================
*/

import Foundation

public final class BISDKCoreModule: BISDKModule {
    /// Authorization used to authenticate the user on API requests.
    public var authorization: String? { _authorization }
    
    private var source: BISDKCoreSource?
    private var _authorization: String?
    
    public init() { }
    
    public func startModule() throws {
        let config = try getBISDKConfig()
        let api = BISDKCoreAPI(config)
        
        source = BISDKCoreSource(api, core: self)
    }
    
    /**
     * Performs a platform login with username and password.
     *
     *  - Parameters:
     *      - username: Username for authentication.
     *      - password: Password for authentication.
     *      - organizationId: ID of the organization to authenticate in.
     *      - completion: Handler that returns the fetched `BISDKToken`.
     */
    public func platformLogin(username: String, password: String, organizationId: String, completion: @escaping (BISDKToken?, Error?) -> ()) {
        source?.login(username: username, password: password, organizationId: organizationId) { [weak self] token, error in
            self?._authorization = token?.authorization
            completion(token, error)
        }
    }
    
    /**
     * Performs a platform logout.
     *
     *  - Parameters:
     *      - accessToken: The accessToken of the user to be logged out.
     *      - tokenId: The tokenId of the user to be logged out.
     *      - completion: Handler that returns if the operation was successful or not.
     */
    public func platformLogOut(accessToken: String, tokenId: String, completion: @escaping (Bool?, Error?) -> ()) {
        source?.logOut(accessToken: accessToken, tokenId: tokenId) { [weak self] success, error in
            if success == true {
                self?._authorization = nil
            }
            completion(success, error)
        }
    }
    
    /**
     * Refreshes an expired `BISDKToken`.
     *
     * - Parameters:
     *      - refreshToken: The refreshToken from an expired `BISDKToken`.
     *      - completion: Handler the returns the refreshed `BISDKToken`.
     */
    public func refreshToken(refreshToken: String, completion: @escaping ((BISDKToken?, Error?) -> Void) ) {
        source?.refreshToken(refreshToken:  refreshToken) { [weak self] token, error in
            if let authorization = token?.authorization {
                self?._authorization = authorization
            }
            completion(token, error)
        }
    }
    
    /**
     * Gets an instance of the uploader.
     *
     * - Parameters:
     *      - initialConfig: A `BISDKUploaderInitialConfig` defining how to start the uploader in case this is the first time its being requested. Leave `nil` for defaults.
     *
     * - Returns: The shared instance of `BISDKDefaultUploader`.
     */
    public func getUploader(with initialConfig: BISDKUploaderInitialConfig? = nil) throws -> BISDKDefaultUploader {
        let uploader = BISDKDefaultUploader.shared
        
        if let config = initialConfig {
            uploader.start(with: config)
        } else {
            let coreConfig = try getBISDKConfig()
            let defaultRetry = BISDKUploaderRetryConfig(maxRetry: 3, totalMaxRetry: 12, delay: 30, retryDelay: 5)
            uploader.start(with: BISDKUploaderInitialConfig(config: coreConfig, retry: defaultRetry))
        }
        
        return uploader
    }
}
