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

import Foundation

class TaskQueueManager {
    private let queue: OperationQueue
    
    
    
    var isAvailability:Bool {
        get {
            if queue.operationCount <= queue.maxConcurrentOperationCount {
                return true
            }
            return false
        }
    }
    
    init(maxConcurrentOperationCount: Int = OperationQueue.defaultMaxConcurrentOperationCount) {
        queue = OperationQueue()
        queue.maxConcurrentOperationCount = maxConcurrentOperationCount
    }
    
    func addTask(_ task: @escaping TSBaseOperation.TaskBlock) -> TSBaseOperation {
        let operation = TSBaseOperation(task: task)
        queue.addOperation(operation)
        return operation
    }
    
    func cancelAllOperations() {
        queue.cancelAllOperations()
    }
    
    func waitUntilAllOperationsAreFinished() {
        queue.waitUntilAllOperationsAreFinished()
    }
    
    
    
    
    //// 监听 operationCount 属性
    //queue.addObserver(self, forKeyPath: "operationCount", options: [.new], context: nil)
    //override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    //    if keyPath == "operationCount" {
    //        if queue.operationCount == 0 {
    //            print("所有任务已完成")
    //        } else {
    //            print("队列中还有 \(queue.operationCount) 个任务在执行")
    //        }
    //    }
    //}
    //
    //deinit {
    //  queue.removeObserver(self, forKeyPath: "operationCount")
    //}
}
