//
//  SDLThrottler.swift
//  Tun
//
//  Created by 安礼成 on 2024/6/3.
//

import Foundation
import Combine

// 限流器
actor SDLThrottler {
    private var limit: Int
    private var token: Int
    private var cancel: AnyCancellable?
    
    init(limit: Int) {
        self.limit = limit
        self.token = limit
    }
    
    func start() {
        self.cancel?.cancel()
        self.cancel = Timer.publish(every: 1.0, on: .main, in: .common).autoconnect()
            .sink { _ in
                Task {
                    self.token = self.limit
                }
            }
    }
    
    func setRateLimit(limit: Int) {
        self.limit = limit
    }
    
    func getToken(num: Int) -> Bool {
        if token > 0 {
            self.token = self.token - num
            return true
        } else {
            return false
        }
    }
    
}
