//
//  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 ([XTLogConfig levelForName:self.name] > 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

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

+ (instancetype)loggerForName:(NSString *)name
{
	XTLogger *logger = [XTLogConfig loggerForName:name];
	return logger;
}

+ (instancetype)loggerForClass:(Class)aClass
{
	NSString *className = NSStringFromClass(aClass);
	XTLogger *logger = [XTLogger loggerForName: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
