//
/* 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 : BISDKUploaderContentManager
* Description : 
* Author: Arnold Dominguez
* Copyright © : Brightinsight, Inc.
* -----------------------
* Revision Change
* -----------------------
* Author                        Date             Version            Change-Description
 Arnold Dominguez       08/10/21            1.0                 Creation
 Arnold Dominguez       09/15/21            1.1                 Documentation
*========================================================================================================
*/

import Foundation
import CoreData

class BISDKUploaderContentManager {
    private let storageManager: BISDKUploaderStorageManager
    
    init(storageManager: BISDKUploaderStorageManager) {
        self.storageManager = storageManager
    }

    func save(record: BISDKUploaderRecord) {
        storageManager.create(fields: fields(from: record), asEntitiesOf: record.recordType)
    }
    
    func fetchRecords(of type: BISDKUploaderRecordType, using predicate: NSPredicate?) -> [BISDKUploaderRecord] {
        guard let items = storageManager.read(entitiesOf: type, using: predicate) else { return [] }

        return items.compactMap({ self.record(from: $0) })
    }
    
    func fetchRecord(of type: BISDKUploaderRecordType, with id: UUID) -> BISDKUploaderRecord? {
        let predicate = NSCompoundPredicate(type: .and, subpredicates: [NSPredicate(format: "id == %@", id as CVarArg)])
        
        return fetchRecords(of: type, using: predicate).first
    }
    
    func update(record: BISDKUploaderRecord) {
        let predicate = NSPredicate(format: "id == %@", record.id as CVarArg)
        
        storageManager.update(fields: fields(from: record), forEntitiesOf: record.recordType, using: predicate)
    }
    
    func deleteRecord(of type: BISDKUploaderRecordType, with id: UUID) {
        let predicate = NSPredicate(format: "id == %@", id as CVarArg)
        
        storageManager.delete(entitiesOf: type, using: predicate)
    }
}

private extension BISDKUploaderContentManager {
    enum Attribute: String {
        case id, payload, eventDate, eventType, lastAttempt, nextRetry, uploadRetries, uploadSuspended, totalUploadRetries
    }
    
    func fields(from record: BISDKUploaderRecord) -> [String:Any?] {
        return [
            Attribute.id.rawValue: record.id,
            Attribute.payload.rawValue: record.payload,
            Attribute.eventDate.rawValue: record.eventDate,
            Attribute.eventType.rawValue: record.recordType.rawValue,
            Attribute.lastAttempt.rawValue: record.lastAttempt,
            Attribute.nextRetry.rawValue: record.nextRetry,
            Attribute.uploadRetries.rawValue: record.uploadRetries,
            Attribute.totalUploadRetries.rawValue: record.totalUploadRetries
        ]
    }
    
    func record(from object: NSManagedObject) -> BISDKUploaderRecord? {
        guard
            let id = object.value(forKey: Attribute.id.rawValue) as? UUID,
            let payload = object.value(forKey: Attribute.payload.rawValue) as? String,
            let eventDate = object.value(forKey: Attribute.eventDate.rawValue) as? Date,
            let typeRaw = object.value(forKey: Attribute.eventType.rawValue) as? String,
            let type = BISDKUploaderRecordType(rawValue: typeRaw)
            else { return nil }
        
        let lastAttempt = object.value(forKey: Attribute.lastAttempt.rawValue) as? Date
        let nextRetry = object.value(forKey: Attribute.nextRetry.rawValue) as? Date
        let uploadRetries = object.value(forKey: Attribute.uploadRetries.rawValue) as? Int
        let uploadSuspended = object.value(forKey: Attribute.uploadSuspended.rawValue) as? Int
        let totalUploadRetries = object.value(forKey: Attribute.totalUploadRetries.rawValue) as? Int
        
        return BISDKUploaderRecord(
            id: id,
            payload: payload,
            eventDate: eventDate,
            type: type,
            lastAttempt: lastAttempt,
            nextRetry: nextRetry,
            uploadRetries: uploadRetries ?? 0,
            uploadSuspended: uploadSuspended ?? 0,
            totalUploadRetries: totalUploadRetries ?? 0
        )
    }
}
