//
//  LNDelayTask.swift
//  Lanu
//
//  Created by OneeChan on 2025/11/6.
//

import Foundation

class LNDelayTask {
    // 保存任务实例，用于取消
    private static let lock = NSLock()
    private static var workItems: [String: DispatchWorkItem] = [:]
    
    /// 执行延时任务（可取消）
    /// - Parameters:
    ///   - delay: 延时秒数
    ///   - queue: 执行队列（默认主线程）
    ///   - task: 延时后执行的任务
    @discardableResult
    static func perform(delay: TimeInterval, queue: DispatchQueue = .main, task: @escaping () -> Void) -> String {
        // 创建任务
        let uuid = UUID().uuidString
        let workItem = DispatchWorkItem(block: {
            lock.lock()
            workItems.removeValue(forKey: uuid)
            lock.unlock()
            
            task()
        })
        lock.lock()
        workItems[uuid] = workItem
        lock.unlock()
        
        // 延时执行
        queue.asyncAfter(deadline: .now() + delay, execute: workItem)
        
        return uuid
    }
    
    /// 取消延时任务
    static func cancel(key: String?) {
        guard let key else { return }
        
        lock.lock()
        defer {
            lock.unlock()
        }
        guard let task = workItems.removeValue(forKey: key) else {
            return
        }
        
        task.cancel()
    }
}
