//
//  TSBaseOperationQueue.swift
//  AIRingtone
//
//  Created by 100Years on 2025/3/20.
//

import Foundation
import Combine



class TSBaseOperationQueue {
    
    private(set) var queue: OperationQueue = OperationQueue()
    
    private var activeOperations:[String:TSBaseOperation] = [:]
    // 存储每个操作的 AnyCancellable
    private var cancellables: [String: AnyCancellable] = [:]
    // 存储 KVO 观察者
    private var operationCountObservation: NSKeyValueObservation?
    
    var isAvailability:Bool{
        if queue.operationCount < queue.maxConcurrentOperationCount {
            return true
        }
        return false
    }

    init(maxConcurrentOperationCount: Int = 1) {
        var maxCount = maxConcurrentOperationCount
//#if DEBUG
//        maxCount = 6
//#endif
        queue.maxConcurrentOperationCount = maxCount
        dePrint("TSBaseOperationQueue operationCountObservation")
        // 监听 operationCount 的变化
           operationCountObservation = queue.observe(\.operationCount, options: [.new]) { [weak self] (queue, change) in
               guard let _ = self else { return }
               if let _ = change.newValue {
                   NotificationCenter.default.post(name: .kBaseOperationQueueCountChanged, object: nil, userInfo: nil)
               }
           }
    }

    func creatOperation(uuid: String, type: TSBaseOperation.Type) -> TSBaseOperation {
        if let existingOperation = activeOperations[uuid] {
            return existingOperation
        } else {
            // 使用 type 参数创建操作
            let operation = type.init(uuid: uuid)
            activeOperations[uuid] = operation
            queue.addOperation(operation)
            dePrint("TSBaseOperationQueue addOperation \(operation)")
            cancellables[uuid] = operation.$operationStatePblished.sink { [weak self] state in
                guard let self = self else { return }
                
                switch state {
                case .finished(let finished):
                    if finished == true {
                        clearOperationsData(uuid: uuid)
                    }
                case .cancelled(let cancelled):
                    if cancelled == true {
                        clearOperationsData(uuid: uuid)
                    }
                default: break
                }
                
                dePrint("TSBaseOperationQueue $operationStatePblished =\(state)")
            }
            return operation
        }
    }
    
    func findOperation<T: TSBaseOperation>(uuid: String) -> T? {
        if let existingOperation = activeOperations[uuid] as? T {
            return existingOperation
        }
        return nil
    }
    
    /// 清理所有下载任务
    func cancelAllOperations() {
        queue.cancelAllOperations()
        activeOperations = [:]
    }
    
    /// 清理某个下载任务
    /// - Parameter url: 下载任务的 URL
    func cancelOperations(uuid: String) {
        if let operation = activeOperations[uuid] {
            operation.cancel()
            clearOperationsData(uuid: uuid)
        }
    }

    func clearOperationsData(uuid: String) {
        dePrint("TSBaseOperationQueue cancelOperations activeOperations 前=\(activeOperations)")
        dePrint("TSBaseOperationQueue cancelOperations cancellables 前=\(cancellables)")
        activeOperations.removeValue(forKey: uuid)
        cancellables.removeValue(forKey: uuid)
        dePrint("TSBaseOperationQueue cancelOperations activeOperations 后=\(activeOperations)")
        dePrint("TSBaseOperationQueue cancelOperations cancellables 后=\(cancellables)")
    }
    func waitUntilAllOperationsAreFinished() {
        queue.waitUntilAllOperationsAreFinished()
    }

}
