//
//  BSUObjectCache.swift
//  UnityFramework
//
//  Created by Moin Hasan on 5/21/25.
//

import Foundation

@objc(BSUObjectCache)
public class BSUObjectCache: NSObject {
    // Singleton instance
    @objc public static let sharedInstance = BSUObjectCache()

    // For backwards compatibility
    @objc public var references: BSUObjectCache { return self }

    // Internal storage
    private var internalReferences: [String: Any] = [:]
    private let lockQueue = DispatchQueue(label: "BSUObjectCache lock queue")

    // Set object for key
    @objc public func setObject(_ object: Any?, forKey key: String) {
        lockQueue.async {
            self.internalReferences[key] = object
        }
    }

    // Get object for key
    @objc public func object(forKey key: String) -> Any? {
        var object: Any?
        lockQueue.sync {
            object = self.internalReferences[key]
        }
        return object
    }

    // Subscript support
    @objc public subscript(key: String) -> Any? {
        get { object(forKey: key) }
        set { setObject(newValue, forKey: key) }
    }

    // Remove object for key
    @objc public func removeObject(forKey key: String) {
        lockQueue.async {
            self.internalReferences.removeValue(forKey: key)
        }
    }
}

// NSObject extension for reference key
@objc public extension NSObject {
    var BSU_referenceKey: String {
        return String(format: "%p", unsafeBitCast(self, to: Int.self))
    }
}
