#import "RTKLogger.h"

@implementation RTKLogger

+ (instancetype)sharedInstance {
    static RTKLogger *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
        sharedInstance.loggingEnabled = NO;
        sharedInstance.minimumLogLevel = RTKLogLevelDebug;
    });
    return sharedInstance;
}

+ (void)verbose:(NSString *)format, ... {
    va_list args;
    va_start(args, format);
    [self log:RTKLogLevelVerbose format:format arguments:args];
    va_end(args);
}

+ (void)debug:(NSString *)format, ... {
    va_list args;
    va_start(args, format);
    [self log:RTKLogLevelDebug format:format arguments:args];
    va_end(args);
}

+ (void)info:(NSString *)format, ... {
    va_list args;
    va_start(args, format);
    [self log:RTKLogLevelInfo format:format arguments:args];
    va_end(args);
}

+ (void)warning:(NSString *)format, ... {
    va_list args;
    va_start(args, format);
    [self log:RTKLogLevelWarning format:format arguments:args];
    va_end(args);
}

+ (void)error:(NSString *)format, ... {
    va_list args;
    va_start(args, format);
    [self log:RTKLogLevelError format:format arguments:args];
    va_end(args);
}

+ (void)log:(RTKLogLevel)level format:(NSString *)format, ... {
    va_list args;
    va_start(args, format);
    [self log:level format:format arguments:args];
    va_end(args);
}

+ (void)log:(RTKLogLevel)level format:(NSString *)format arguments:(va_list)args {
    RTKLogger *logger = [RTKLogger sharedInstance];
    
    if (!logger.loggingEnabled) {
        return;
    }
    
    if (level < logger.minimumLogLevel) {
        return;
    }
    
    NSString *message = [[NSString alloc] initWithFormat:format arguments:args];
    NSString *levelString = [self stringForLogLevel:level];
    NSString *logMessage = [NSString stringWithFormat:@"[RTK][%@] %@", levelString, message];
    
    NSLog(@"%@", logMessage);
}

+ (NSString *)stringForLogLevel:(RTKLogLevel)level {
    switch (level) {
        case RTKLogLevelVerbose:
            return @"VERBOSE";
        case RTKLogLevelDebug:
            return @"DEBUG";
        case RTKLogLevelInfo:
            return @"INFO";
        case RTKLogLevelWarning:
            return @"WARNING";
        case RTKLogLevelError:
            return @"ERROR";
        case RTKLogLevelNone:
            return @"NONE";
        default:
            return @"UNKNOWN";
    }
}

+ (void)enable {
    RTKLogger *logger = [RTKLogger sharedInstance];
    logger.loggingEnabled = YES;
    NSLog(@"[RTK][INFO] RealtimeKit logging enabled");
}

+ (void)disable {
    RTKLogger *logger = [RTKLogger sharedInstance];
    NSLog(@"[RTK][INFO] RealtimeKit logging disabled");
    logger.loggingEnabled = NO;
}

@end
