//
/* 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 : BISDKDefaultUploader
* Description : 
* Author: Arnold Dominguez
* Copyright © : Brightinsight, Inc.
* -----------------------
* Revision Change
* -----------------------
* Author                        Date             Version            Change-Description
  Arnold Dominguez       08/17/21            1.0                 Creation
  Arnold Dominguez       09/06/21            1.1                 Refactor for cross-platform design.
  Arnold Dominguez       09/15/21            1.2                 Documentation
*========================================================================================================
*/

import Foundation

public final class BISDKDefaultUploader {
    static var shared: BISDKDefaultUploader = BISDKDefaultUploader()
    
    private var contentManager: BISDKUploaderContentManager!
    
    func start(with initialConfig: BISDKUploaderInitialConfig) {
        guard contentManager == nil else { return }
        
        let database = BISDKDatabase(identifier: "BISDKUploader")
        let storageManager = BISDKUploaderStorageManager(database: database)
        contentManager = BISDKUploaderContentManager(storageManager: storageManager)
        
        BISDKTimedUploader.logging = BISDKTimedUploader(uploader: self, recordType: .log, config: initialConfig.config, settings: initialConfig.retry)
        BISDKTimedUploader.deviceMetadata = BISDKTimedUploader(uploader: self, recordType: .deviceMetadata, config: initialConfig.config, settings: initialConfig.retry)
        BISDKTimedUploader.deviceReading = BISDKTimedUploader(uploader: self, recordType: .deviceObservation, config: initialConfig.config, settings: initialConfig.retry)
    }
}

extension BISDKDefaultUploader: BISDKUploader {
    /**
     Saves a payload into the upload queue.
     - Parameters:
        - payload: Payload as a string.
        - type: Payload type.
        - completion: Handler called with the newly saved record's `UUID`
    */
    public func save(payload: String, for type: BISDKUploaderRecordType, completion: @escaping (UUID) -> Void) {
        let record = BISDKUploaderRecord(payload: payload, type: type)
        
        contentManager.save(record: record)
        completion(record.id)
    }
    
    /**
     Searches for a record with a given id and type.
     - Parameters:
        - id: Identifier of the record.
        - type: Type of the record.
     - Returns: An instance of `BISDKUploaderRecord` if available.
    */
    func getRecord(with id: UUID, of type: BISDKUploaderRecordType) -> BISDKUploaderRecord? {
        return contentManager.fetchRecord(of: type, with: id)
    }
    
    /**
     Searches for all the records of a given type.
     - Parameters:
        - type: Type of the records.
     - Returns: All found `BISDKUploaderRecord`.
    */
    func getRecords(of type: BISDKUploaderRecordType) -> [BISDKUploaderRecord] {
        return fetchRecords(of: type)
    }
    
    /**
     Searches for all records of a given type where `totalUploadRetries` is lower than a given number.
     - Parameters:
        - maxRetryLowerThan: Threshold number to limit the `totalUploadRetries`.
        - type: Record type.
     - Returns: All found `BISDKUploaderRecord`.
    */
    func getRecords(with maxRetryLowerThan: Int, of type: BISDKUploaderRecordType) -> [BISDKUploaderRecord] {
        let condition = "totalUploadRetries < \(maxRetryLowerThan)"
        let condition2 = "nextRetry == nil"
        
        return fetchRecords(of: type, conditions: condition, condition2)
    }
    
    /**
     Updates a given `BISDKUploaderRecord`.
     - Parameters:
        - record: The record to be updated.
     */
    func update(record: BISDKUploaderRecord) {
        contentManager.update(record: record)
    }
    
    /**
     Deletes a given `BISDKUploaderRecord`.
     - Parameters:
        - record: The record to be deleted.
     */
    func delete(record: BISDKUploaderRecord) {
        contentManager.deleteRecord(of: record.recordType, with: record.id)
    }
    
    /**
     Deletes all records with `totalUploadRetries` greater than or equal to a given number.
     - Parameters:
        - maxRetryGreaterThan: Threshold number to limit the `totalUploadRetries`.
        - type: Record type.
     */
    func deleteRecords(with maxRetryGreaterThan: Int, of type: BISDKUploaderRecordType) {
        let records = fetchRecords(of: type, conditions: "totalUploadRetries >= \(maxRetryGreaterThan)")
        records.forEach({ record in
            delete(record: record)
            logRemoved(record: record)
        })
    }
    
    /**
     Generates a description, as `String`, of all records matching a given type.
     - Parameters:
        - type: Record type.
        - completion: Handler called with the generated description.
     */
    public func descriptionForRecords(of type: BISDKUploaderRecordType, completion: @escaping (String) -> Void) {
        DispatchQueue.global().async {
            let records = self.getRecords(of: type)
            
            guard !records.isEmpty else { return completion("Could not find records of type '\(type.rawValue)'") }

            let description: String = records.reduce(into: "", { result, record in
                let lastAttempt = record.lastAttempt?.description ?? "None"
                let nextRetry = record.nextRetry?.description ?? "None"
                
                result.append("---------------------\nId: \(record.id.uuidString)\nPayload: \(record.payload)\nEvent Date: \(record.eventDate)\nEvent Type: \(record.recordType.rawValue)\nUpload Retries: \(record.uploadRetries)\nTotalUploadRetries: \(record.totalUploadRetries)\n\nLast Attempt: \(lastAttempt)\nNext Retry: \(nextRetry)\n")
            })
            
            completion(description)
        }
    }
    
    /**
     Clears all content on the database.
     */
    func cleanStorage() {
        let records = fetchRecords(of: .log) + fetchRecords(of: .deviceMetadata) + fetchRecords(of: .deviceObservation)
        records.forEach { record in
            contentManager.deleteRecord(of: record.recordType, with: record.id)
        }
    }
}

private extension BISDKDefaultUploader {
    func fetchRecords(of type: BISDKUploaderRecordType, conditions: String...) -> [BISDKUploaderRecord] {
        let predicates: [NSPredicate] = conditions.map({ NSPredicate(format: $0) })
        let predicate = NSCompoundPredicate(type: .and, subpredicates: predicates)
        
        let records = contentManager.fetchRecords(of: type, using: predicate)
        
        return records
    }
    func logRemoved(record: BISDKUploaderRecord) {
        let extras = [BISDKLogEvent.CommonKeys.recordType.rawValue: record.recordType.rawValue]
        let logEvent = BISDKLogEvent(event: .BISDKCore_payloadRemoved, type: .info, date: Date(), extras: extras)
        
        guard
            record.recordType != .log,
            let payload = BISDKLogPayloadEncoder.encode(event: logEvent)
        else { return }
        
        save(payload: payload, for: .log) { uuid in
            #if DEBUG
            print("*** Log entity created with ID \(uuid) ***")
            #endif
        }
    }
}
