//
//  TestParser.m
//  ICeCoffEE
//
//  Created by Nicholas Riley on 6/22/07.
//  Copyright 2007 Nicholas Riley. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "ICeCoffEEParser.h"

#include <stdarg.h>

void ps(NSString *format, ...) {
    va_list args;
    va_start(args, format);
    NSString *s = [[NSString alloc] initWithFormat: format arguments: args];
    va_end(args);
    printf("%s\n", [s cString]);
    [s release];
}

void pr(NSString *s, NSRange r) {
    ps([[NSString alloc] initWithFormat: @"%@%@>%@<",
	s, [@"" stringByPaddingToLength: r.location withString: @" " startingAtIndex: 0],
	[@"" stringByPaddingToLength: r.length withString: @"-" startingAtIndex: 0]]);
}

CFBundleRef ICCF_bundle = NULL;

int main(int argc, char *argv[]) {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
    NSArray *a = [NSArray arrayWithContentsOfFile: @"urls.plist"];
    NSCAssert(a != nil, @"Can't get array from urls.plist (wrong cwd? invalid format?)");
    
    ICCF_StartIC();
    
    NSEnumerator *e = [a objectEnumerator];
    NSDictionary *d;
    while ( (d = [e nextObject]) != nil) {
	NSString *uri = [d objectForKey: @"uri"];
	NSString *text = [d objectForKey: @"text"];
	NSCAssert1(uri != nil, @"No URI in test case description %@", d);
	
	NSRange delimitedURIRange;
	if (text != nil) {
	    NSArray *bits = [text componentsSeparatedByString: @"|"];
	    NSCAssert1([bits count] == 3, @"Sample text is not of the form 'foo|bar|baz': %@", text);
	    text = [bits componentsJoinedByString: @""];
	    delimitedURIRange.location = [(NSString *)[bits objectAtIndex: 0] length];
	    delimitedURIRange.length = [(NSString *)[bits objectAtIndex: 1] length];
	} else {
	    text = uri;
	    delimitedURIRange.location = 0;
	    delimitedURIRange.length = [uri length];
	}
	
	// XXX can't yet select by word, so just try a middle-ish character
	NSRange initialSelectionRange = {
	    delimitedURIRange.location + (delimitedURIRange.length / 2),
	    delimitedURIRange.length != 0
	};
	
	// XXX figure XFAIL-type error checking
	
	// XXX figure out a way to plot a range underneath a string, like:
	// foo(https://www-s.acm.uiuc.edu/wiki/space/usermloar2)bar
	//   >--------------------------------------------------<
	ps(@"Text       %@", text);
	pr(@"Available ", delimitedURIRange);
	pr(@"Starting  ", initialSelectionRange);
	
	NSRange enclosingRange = ICCF_URLEnclosingRange(text, delimitedURIRange);
	pr(@"Parsed    ", enclosingRange);
	
	ps(@"Parsed     %@", [text substringWithRange: enclosingRange]);
	ps(@"Desired    %@", uri);
	ps(@"");
    }
    
    ICCF_StopIC();

    [pool release];
}
