//
//  PDNSCurlLogger.m
//  PDNSCurl
//

#import "PDNSCurlLogger.h"

@interface PDNSCurlLogger ()

@property (atomic, assign) PDNSCurlLogLevel currentLogLevel;

@end

@implementation PDNSCurlLogger

+ (instancetype)sharedLogger {
    static PDNSCurlLogger *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[PDNSCurlLogger alloc] init];
    });
    return instance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        // 默认日志级别设为ERROR，生产环境较为安全
        _currentLogLevel = PDNSCurlLogLevelError;
    }
    return self;
}

+ (void)setLogLevel:(PDNSCurlLogLevel)level {
    [PDNSCurlLogger sharedLogger].currentLogLevel = level;
}

+ (PDNSCurlLogLevel)currentLogLevel {
    return [PDNSCurlLogger sharedLogger].currentLogLevel;
}

+ (NSString *)stringForLogLevel:(PDNSCurlLogLevel)level {
    switch (level) {
        case PDNSCurlLogLevelOff:
            return @"OFF";
        case PDNSCurlLogLevelError:
            return @"ERROR";
        case PDNSCurlLogLevelInfo:
            return @"INFO";
        case PDNSCurlLogLevelDebug:
            return @"DEBUG";
        default:
            return @"UNKNOWN";
    }
}

@end

// 全局函数实现，供宏调用
void PDNSCurlLog(PDNSCurlLogLevel level, NSString *component, NSString *format, ...) {
    // 检查是否需要记录此级别的日志
    if (level > [PDNSCurlLogger currentLogLevel]) {
        return;
    }

    // 获取格式化的消息
    va_list args;
    va_start(args, format);
    NSString *message = [[NSString alloc] initWithFormat:format arguments:args];
    va_end(args);

    // 生成时间戳
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss.SSS";
    NSString *timestamp = [formatter stringFromDate:[NSDate date]];

    // 获取日志级别字符串
    NSString *levelString;
    switch (level) {
        case PDNSCurlLogLevelOff:
            levelString = @"OFF";
            break;
        case PDNSCurlLogLevelError:
            levelString = @"ERROR";
            break;
        case PDNSCurlLogLevelInfo:
            levelString = @"INFO";
            break;
        case PDNSCurlLogLevelDebug:
            levelString = @"DEBUG";
            break;
        default:
            levelString = @"UNKNOWN";
            break;
    }

    // 输出格式化的日志消息
    NSLog(@"[%@] [%@] [%@] %@", timestamp, levelString, component, message);
}
