//
//  NSObject+Extension.swift
//  Lanu
//
//  Created by OneeChan on 2025/11/14.
//

import Foundation
import Combine


private final class CancellableBagContainer {
    /// 线程安全的订阅容器
    var cancellables: Set<AnyCancellable> = []
    /// 读写锁（避免多线程操作Set崩溃）
    let lock = NSLock()
}

private var cancellableBagKey: UInt8 = 0
extension NSObject {
    /// 用于存储Combine订阅的容器，自动与对象生命周期绑定
    var cancellables: Set<AnyCancellable> {
        get {
            // 先获取容器实例
            let container: CancellableBagContainer = {
                if let existing = objc_getAssociatedObject(self, &cancellableBagKey) as? CancellableBagContainer {
                    return existing
                }
                let newContainer = CancellableBagContainer()
                objc_setAssociatedObject(self, &cancellableBagKey, newContainer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
                return newContainer
            }()
            // 返回容器内的Set（拷贝，保证值语义）
            return container.cancellables
        }
        set {
            // 获取/创建容器，更新内部Set
            let container: CancellableBagContainer = {
                if let existing = objc_getAssociatedObject(self, &cancellableBagKey) as? CancellableBagContainer {
                    return existing
                }
                let newContainer = CancellableBagContainer()
                objc_setAssociatedObject(self, &cancellableBagKey, newContainer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
                return newContainer
            }()
            container.lock.lock()
            container.cancellables = newValue
            container.lock.unlock()
        }
    }
}

extension NSObject {
    static var className: String {
        String(describing: Self.self)
    }
}
