//
//  SDLFlowTracer.swift
//  Tun
//
//  Created by 安礼成 on 2024/5/27.
//

import Foundation
import Darwin

// 流量统计器
final class SDLFlowTracer {
    enum FlowType {
        case forward
        case p2p
        case inbound
    }
    
    private var forwardFlowBytes: UInt32 = 0
    private var p2pFlowBytes: UInt32 = 0
    private var inFlowBytes: UInt32 = 0
    
    private let lock = NSLock()
    
    func inc(num: Int, type: FlowType) {
        lock.lock()
        defer {
            lock.unlock()
        }
        
        switch type {
        case .inbound:
            self.inFlowBytes += UInt32(num)
        case .forward:
            self.forwardFlowBytes += UInt32(num)
        case .p2p:
            self.p2pFlowBytes += UInt32(num)
        }
    }
    
    func reset() -> (UInt32, UInt32, UInt32) {
        lock.lock()
        defer {
            self.forwardFlowBytes = 0
            self.inFlowBytes = 0
            self.p2pFlowBytes = 0
            lock.unlock()
        }
        
        return (forwardFlowBytes, p2pFlowBytes, inFlowBytes)
    }
}
