//
//  XTLogger.m
//  TadsTerp
//
//  Created by Rune Berg on 14/04/14.
//  Copyright (c) 2014 Rune Berg. All rights reserved.
//

#import "XTLogger.h"
#import "XTLogConfig.h"
#import "XTLogAppenderProtocol.h"


#define XTLOGGER_LOG(entryLevel) \
	if (self.level > entryLevel) { \
		return; \
	} \
	\
	NSArray *appenders = [XTLogConfig appendersForName:self.name]; \
	if (appenders.count == 0) { \
		return; \
	} \
	\
	va_list args; \
	va_start(args, format); /* format being the last arg before the var args */ \
	NSString *msg = [[NSString alloc] initWithFormat:format arguments:args]; \
	va_end(args); \
	\
	for (id<XTLogAppenderProtocol> app in appenders) { \
		[app appendToLog:self.name msg:msg level:entryLevel]; \
	}


@implementation XTLogger

static NSMutableDictionary *loggerByName;

+ (void)initialize
{
	loggerByName = [NSMutableDictionary dictionary];
}

- (id)initWithName:(NSString *)name
 {
	 self = [super init];
	 if (self) {
		 _name = name;
		 _level = [XTLogConfig levelForName:name];
	 }
	 return self;
 }

+ (instancetype)loggerNamed:(NSString *)name
{
	XTLogger *logger = loggerByName[name];
	if (logger == nil) {
		logger = [[XTLogger alloc] initWithName:name];
		loggerByName[name] = logger;
	}
	return logger;
}

+ (instancetype)loggerForClass:(Class)aClass
{
	NSString *className = NSStringFromClass(aClass);
	XTLogger *logger = [XTLogger loggerNamed:className];
	return logger;
}

- (void)trace:(NSString *)format, ...
{
	XTLOGGER_LOG(XT_LEVEL_TRACE)
}

- (void)debug:(NSString *)format, ...
{
	XTLOGGER_LOG(XT_LEVEL_DEBUG)
}

- (void)info:(NSString *)format, ...
{
	XTLOGGER_LOG(XT_LEVEL_INFO)
}

- (void)warn:(NSString *)format, ...
{
	XTLOGGER_LOG(XT_LEVEL_WARN)
}

- (void)error:(NSString *)format, ...
{
	XTLOGGER_LOG(XT_LEVEL_ERROR)
}

- (void)fatal:(NSString *)format, ...
{
	XTLOGGER_LOG(XT_LEVEL_FATAL)
}

@end
