/* Copyright (c) 2011 Artjom Popov */

#import "UTScannerResult.h"

NSString *UTScannerResultErrorDomain = @"UTScannerResultError";

@implementation UTScannerResult

- (id)initWithCode:(NSString *)code points:(NSArray *)points error:(NSError **)error
{
	//NSLog(@"Code: %@", code);
	
	self = [super init];
	
	if(self) {
		NSMutableArray *fields = [NSMutableArray array];
		NSArray *components = [code componentsSeparatedByString:@"|"];
		
		if (components.count < 2) {
			*error = [NSError errorWithDomain:UTScannerResultErrorDomain code:1 userInfo:nil];
			return nil;
		} else {
			// First component should begin with '@'
			NSString *component = [components objectAtIndex:0];
			if (component.length > 11 && [component characterAtIndex:0] != '@') {
				*error = [NSError errorWithDomain:UTScannerResultErrorDomain code:1 userInfo:nil];
				return nil;
			}
		}
		
		for (NSString *value in components) {
			if (value.length > 11 && [value characterAtIndex:0] == '@') {
				self->m_eventCode = [[[value substringFromIndex:1] substringToIndex:10] retain];
				self->m_identifier = [[value substringFromIndex:11] retain];
			} else {
				[fields addObject:value];
			}
		}
		
		self->m_data = [fields retain];
		self->m_code = [code retain];
		self->m_points = [points retain];
	}
	
	return self;
}

@synthesize identifier = m_identifier;
@synthesize eventCode = m_eventCode;
@synthesize data = m_data;
@synthesize code = m_code;
@synthesize points = m_points;

#pragma mark NSObject

- (void)dealloc
{
	[self->m_identifier release];
	[self->m_eventCode release];
	[self->m_data release];
	[self->m_code release];
	[self->m_points release];
	
	[super dealloc];
}

@end
