//
//  SDLLogger.swift
//  Tun
//
//  Created by 安礼成 on 2024/3/13.
//
import Foundation
import os

public class SDLLogger: @unchecked Sendable {
    
    public enum Subsystem: String, CaseIterable {
        case debug = "com.jihe.punchnet.debug"
        case trace = "com.jihe.punchnet.trace"
    }
    
    private static let debugLoggingEnabled = ProcessInfo.processInfo.environment["SDL_DEBUG_LOG"] != "0"
    private static let traceLoggingEnabled = ProcessInfo.processInfo.environment["SDL_TRACE_LOG"] == "1"
    private static let loggers: [Subsystem: SDLLogger] = {
        Dictionary(uniqueKeysWithValues: Subsystem.allCases.map { ($0, SDLLogger(subsystem: $0)) })
    }()
    
    private let log: Logger
    
    private init(subsystem: Subsystem) {
        self.log = Logger(subsystem: subsystem.rawValue, category: "punchnet")
    }
    
    public func _log(_ message: String) {
        self.log.info("\(message, privacy: .public)")
    }
    
    public static func log(_ message: @autoclosure () -> String, for system: Subsystem = .debug) {
        guard self.isEnabled(system), let logger = loggers[system] else {
            return
        }

        logger._log(message())
    }

    private static func isEnabled(_ system: Subsystem) -> Bool {
        switch system {
        case .debug:
            return self.debugLoggingEnabled
        case .trace:
            return self.traceLoggingEnabled
        }
    }
}
