//
//  MatchingPair.m
//  ArcParser
//
//  Created by the cell on 5/31/07.
//  Copyright 2007 __MyCompanyName__. All rights reserved.
//

#import "MatchingPair.h"

NSString *string = nil;
int firstLocation;
int secondLocation;
RepetitionRegion *partOfRepetitionRegion = nil;

@implementation MatchingPair

- (id)initWithString:(NSString *)aString firstLocation:(int)aFirstLocation secondLocation:(int)aSecondLocation
{
	[super init];
	
	[aString retain];
	string = aString;
	firstLocation = aFirstLocation;
	secondLocation = aSecondLocation;
	
	//do string and length match?
	if (firstLocation + [string length] > secondLocation)
	{
		return nil;
	}

	return self;
}

- (NSString *)string
{
	return string;
}

- (int)length
{
	return (secondLocation + [string length]) - firstLocation;
}

- (int)stringLength
{
	return [string length];
}

- (int)firstLocation
{
	return firstLocation;
}

- (int)secondLocation
{
	return secondLocation;
}

- (NSRange)firstRange
{
	return NSMakeRange(firstLocation, [string length]);
}

- (NSRange)secondRange
{
	return NSMakeRange(secondLocation, [string length]);
}

- (void)setPartOfRepetitionRegion:(RepetitionRegion *)aRepetitionRegion
{
	[aRepetitionRegion retain];
	partOfRepetitionRegion = aRepetitionRegion;
}

- (RepetitionRegion *)repetitionRegion
{
	return partOfRepetitionRegion;
}

- (BOOL)isPartOfARepetitionRegion
{
	if (partOfRepetitionRegion)
	{
		return YES;
	}
	
	return NO;
}

- (int)distanceFromFirstLocationToSecondLocation
{
	return secondLocation - firstLocation;
}

- (int)distanceBetweenStrings
{
	return secondLocation - (firstLocation + [string length]);
}

- (BOOL)contains:(MatchingPair *)aMatchingPair
{
	//abcdXabcd contains XbcXXXbcX
	if ((NSIntersectionRange([aMatchingPair firstRange], [self firstRange]).length == [aMatchingPair stringLength]) && (NSIntersectionRange([aMatchingPair secondRange], [self secondRange]).length == [aMatchingPair stringLength]))
	{
		if ([self equals:aMatchingPair])
		{
			return NO;
		}
		else
		{
			return YES;
		}

	}
	
	return NO;
}

- (BOOL)equals:(MatchingPair *)aMatchingPair
{
	if ([string isEqualToString:[aMatchingPair string]] && firstLocation == [aMatchingPair firstLocation] && secondLocation == [aMatchingPair secondLocation])
	{
		return YES;
	}
	
	return NO;
}

- (void)printToLog
{
	if (string)
	{
		NSLog(@"MatchingPair, string: '%@' firstLocation: %i secondLocation: %i", string, firstLocation, secondLocation);
		if (partOfRepetitionRegion)
		{
			NSLog(@"> part of:");
			[partOfRepetitionRegion printToLog];
		}
		NSLog(@"---");
	}
	else
	{
		NSLog(@"MatchingPair not properly initialised.");
	}
}

@end
