#import "BWMainObject.h"
#import "BWOverWorld.h"
#import "BWGameData.h"
#import "BWSideView.h"
#import "Variables.h"

@implementation BWMainObject

# pragma mark -

- (void)awakeFromNib
{
	path = nil;
	romData = nil;
}

# pragma mark -

- (IBAction)open:(id)sender
{
	int r;
	NSOpenPanel *op = [NSOpenPanel openPanel];
	r = [op runModalForTypes:[NSArray arrayWithObject:@"nes"]];
	if (r == NSOKButton) {
		
		if (path != nil) [path release];
		path = [[NSString alloc] initWithString:[[op filenames] lastObject]];
		
		if (romData != nil) [romData release];
		romData = [[NSMutableData alloc] initWithContentsOfFile:path];
		NSLog(@"romData length : %X",[romData length]);
		NSLog(@"----");
		
		[objOverWorld open:romData];
		//[objGameData open:romData];
		[objSideView open:romData];
	}
	
	/*unsigned const char *ptr = [romData bytes] + 0x48B0;
	unsigned char n,x,y,t;
	int i,j;
	
	for (i=0; i<0x7E; i++) {	// 7E
		
		n = (*ptr - 1) / 2;
		NSLog(@"Set %X\t%X Enemy",i,n);
		ptr++;
		
		for (j=0; j<n; j++) {
			
			x = (*ptr & 0x0F) | ((*(ptr+1) & 0xC0) >> 2);
			y = ((*ptr & 0xF0) >> 4);
			if (y != 1) y += 2;
			t = *(ptr+1) & 0x3F;
			NSLog(@"%X %X\t%X,%X - %X",*ptr,*(ptr+1),x,y,t);
			ptr += 2;
			
		}
		NSLog(@"----");
	}*/
}

- (IBAction)save:(id)sender
{
	//[objOverWorld save];
	//[objGameData save];
	//[objSideView save];
	
	if ([romData writeToFile:path atomically:YES]) NSLog(@"Save - OK");
	else NSLog(@"Save - Error");
}

# pragma mark -

- (NSColor *)colorForCode:(unsigned char)code
{
	NSColor *color;
	struct sCol tp = nesPal[code];
	float r,g,b;
	
	if (code > 0x3F) code = 0x3F;
	r = (float)tp.r / 255.0;
	g = (float)tp.g / 255.0;
	b = (float)tp.b / 255.0;
	color = [NSColor colorWithDeviceRed:r green:g blue:b alpha:1.0];
	
	return color;
}

# pragma mark -

- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender
{
	//int i;
	if (romData) {
		//i = NSRunAlertPanel(@"Do you want to save before quitting ?",@"",@"Save",@"Cancel",@"Don't Save");
		//if (i == NSAlertAlternateReturn) return NO;
		//else if (i == NSAlertOtherReturn) return YES;
		//else {
		[self save:nil];
		return YES;
		//}
	} else {
		return YES;
	}
}

@end

