#import "theBrain.h"

@implementation theBrain

- (void)awakeFromNib
{
	path = [[NSMutableString alloc] initWithCapacity:32];
	textStrings = [[NSMutableArray alloc] initWithCapacity:5];
	
	[self open:nil];
	canSave = YES;
}

- (IBAction)open:(id)sender
{
	int r;
	NSOpenPanel *op = [NSOpenPanel openPanel];
	r = [op runModalForTypes:nil];
	if (r == NSOKButton) {
		
		[path setString:[[op filenames] lastObject]];
		if (rom) [rom release];
		rom = [[NSMutableData alloc] initWithContentsOfFile:path];
		// Eventually check if the file is good, even if we don't really care...
		
		[self setMagic];
		[self setMagicNames];
		[self setLevels];
		[self setLevelsNames];
		[self setTextStrings];
		
	}
}

/*- (IBAction)open:(id)sender
{
	rom = [[NSMutableData alloc] initWithContentsOfFile:@"/Users/sim/Desktop/Projets/ZIIGameEditor/Zelda2Magic.nes"];
	//rom = [[NSMutableData alloc] initWithContentsOfFile:@"/Users/sim/Desktop/Simon/Nin/Zelda 2 Fr.nes"];
	
	[self setMagic];
	[self setMagicNames];
	[self setLevels];
	[self setLevelsNames];
	[self setTextStrings];
}*/

- (IBAction)save:(id)sender
{
	[self saveMagic];
	[self saveLevels];
	[self saveText];
	
	if ([rom writeToFile:path atomically:YES])
		NSLog(@"Save - OK");
	else
		NSLog(@"Save - Error");
}

- (void)setMagic
{
	const char *ptr = [rom bytes];
	ptr += 0x0D8B;
	
	int i;
	unsigned char v;
	for (i=0; i<64; i++) {
		
		v = *ptr++;
		[[matrixMagic cellWithTag:i] setIntValue:(v / 2)];
		
	}
}

- (void)setMagicNames
{
	unsigned char name[8];
	const char *ptr = [rom bytes];
	ptr += 0x1C3A;
	
	int i,j;
	for (i=0; i<8; i++) {
	
		for (j=0; j<8; j++) {
			name[j] = *ptr++;
			name[j] = [self toASCII:name[j]];
		}
	
	NSString *str = [NSString stringWithCString:(const char *)name length:8];
	[[matrixMagicNames cellAtRow:i column:0] setStringValue:str];
	ptr += 6;
	
	}
}

- (void)saveMagic
{
	const char *ptr;
	unsigned char v;
	ptr = &v;
	
	int i;
	for (i=0; i<64; i++) {
		
		v = ([[matrixMagic cellWithTag:i] intValue] * 2);
		[rom replaceBytesInRange:NSMakeRange( 0x0D8B + i , 1 ) withBytes:ptr];
		
	}
	
	NSMutableString *name = [NSMutableString stringWithCapacity:8];
	unsigned char w[8];
	ptr = &w[0];
	
	int j;
	for (i=0; i<8; i++) {
		[name setString:[[matrixMagicNames cellWithTag:i] stringValue]];
		for (j=0; j<8; j++) {
			w[j] = [self fromASCII:[name characterAtIndex:j]];
		}
		[rom replaceBytesInRange:NSMakeRange( 0x1C3A + (i * 14) , 8 ) withBytes:ptr];
		ptr = &w[0];
	}
}

- (void)setLevels
{
	unsigned short c;
	unsigned char b1,b2;
	const char *ptr = [rom bytes];
	ptr += 0x1669;
	
	int i;
	for (i=0; i<24; i++) {
		
		b1 = *ptr;
		b2 = *(ptr + 24);
		c = b1 * 256 + b2;
		[[matrixLevels cellWithTag:i] setIntValue:c];
		ptr++;
		
	}
}

- (void)setLevelsNames
{
	unsigned char name[8];
	const char *ptr = [rom bytes];
	NSString *str;
	int i,j;
	
	ptr += 0x1BF9;
	for (i=0; i<3; i++) {
		for (j=0; j<6; j++) { name[j] = [self toASCII:*ptr++]; }
		str = [NSString stringWithCString:(const char *)name length:6];
		[[matrixLevelsNames cellWithTag:i] setStringValue:str];
		ptr += 8;
	}
}

- (void)saveLevels
{
	const char *ptr;
	unsigned char v[48];
	unsigned short t;
	ptr = &v[0];
	
	int i;
	for (i=0; i<24; i++) {
		
		t = [[matrixLevels cellWithTag:i] intValue];
		NSLog(@"t = %X",t);
		v[i] = (t >> 8);
		v[i+24] = t;
		NSLog(@"v = %X%X",v[i],v[i+24]);
		
	}
	
	[rom replaceBytesInRange:NSMakeRange( 0x1669 , 48 ) withBytes:ptr];
}

- (void)setTextStrings
{
	const char *ptr = [rom bytes];
	const char *str;
	ptr += 0xEFCE;
	unsigned short int t = 0;
	unsigned char s[40];
	NSString *final;
	NSMutableArray *dialogs = [NSMutableArray arrayWithCapacity:98];
	
	int i,j;
	for (i=0; i<98; i++) {
		
		t = *ptr & 0x00FF;
		t += *(ptr + 1) << 8;
		t += 0x4010;
		
		str = [rom bytes];
		str += t;
		
		j = 0;
		while (1) {
			s[j] = *str++;
			if (s[j] == 0xFF) break;
			s[j] = [self toASCII:s[j]];
			j++;
		}
		
		final = [NSString stringWithCString:(const char *)s length:j];
		[dialogs addObject:final];
		
		ptr += 2;
	}
	
	//NSLog(@"final : \r%@",[dialogs description]);
	
	NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:dialogs,@"List",@"DIALOGS",@"Name",nil];
	[textStrings addObject:dict];
}

- (IBAction)showText:(id)sender
{
	int s = [sender selectedRowInColumn:1];
	
	if (s == -1) {
		[fieldText setString:@" "];
		[fieldText setEditable:NO];
		[fieldText setSelectable:NO];
	} else {
		NSArray *list = [[textStrings objectAtIndex:[sender selectedRowInColumn:0]] objectForKey:@"List"];
		[fieldText setString:[list objectAtIndex:s]];
		[fieldText setSelectable:YES];
		[fieldText setEditable:YES];
	}
}

- (IBAction)confirmText:(id)sender
{
	int s = [browserText selectedRowInColumn:1];
	NSLog(@"s : %d",s);
	
	if (s >= 0) {
		NSMutableArray *list = [[textStrings objectAtIndex:[browserText selectedRowInColumn:0]] objectForKey:@"List"];
		NSString *bla = [NSString stringWithString:[fieldText string]];
		NSLog(@"bla : %@",bla);
		[list replaceObjectAtIndex:s withObject:bla];
		[browserText reloadColumn:1];
		[browserText selectRow:s inColumn:1];
	}
}

- (void)saveText
{
	unsigned short int pt;		// Location of text data
	unsigned short int pp;		// Location of text pointers
	unsigned short int vp;		// Value of the current pointer
	unsigned char s[40];
	NSArray *list = [[textStrings objectAtIndex:0] objectForKey:@"List"];
	NSString *str;
	
	pt = 0xE390;
	pp = 0xEFCE;
	
	int i,j;
	for (i=0; i<98; i++) {
		
		NSLog(@"--------");
		str = [list objectAtIndex:i]; NSLog(@"%@",str);
		if ((pt + [str length]) >= 0xEFCE) pt = 0xF830;
		
		vp = pt - 0x4010;
		vp = (vp << 8) | (vp >> 8);
		
		for (j=0; j<[str length]; j++) {
			s[j] = [self fromASCII:[str characterAtIndex:j]];
			//NSLog(@"s = %X",s[j]);
		}
		
		s[j] = 0xFF;
		j++;
		
		NSLog(@"pt : %X",pt);
		NSLog(@"vp : %X",vp);
		
		[rom replaceBytesInRange:NSMakeRange( pt , j ) withBytes:s];
		[rom replaceBytesInRange:NSMakeRange( pp , 2 ) withBytes:&vp];
		
		pt += j;
		pp += 2;
	}
}

- (void)textDidChange:(NSNotification *)notif
{
	NSString *str = [fieldText string];
	
	char c;
	int a = 0;
	int i;
	for (i=0; i<[str length]; i++) {
		
		if ([str length] > 43) {
			[fieldText setTextColor:[NSColor redColor]];
			NSBeep();
			break;
		}
		
		a++;
		
		c = [str characterAtIndex:i];
		
		if (c == 0x0A) a = 0;
		
		if (a > 10) {
			[fieldText setTextColor:[NSColor redColor]];
			NSBeep();
			break;
		} else {
			[fieldText setTextColor:[NSColor blackColor]];
		}
	}
}

- (unsigned char)toASCII:(unsigned char)ctc
{
	if (ctc >= 0xDA && ctc <= 0xF3) ctc -= 153;
	if (ctc >= 0xD0 && ctc <= 0xD9) ctc -= 160;
	if (ctc == 0x34) ctc = '?';
	if (ctc == 0x36) ctc = '!';
	if (ctc == 0x9C) ctc = ',';
	if (ctc == 0xCF) ctc = '.';
	if (ctc == 0xF4) ctc = ' ';
	if (ctc == 0xF6) ctc = '-';
	if (ctc == 0xFD) ctc = 0x0A;
	if (ctc == 0xFE) ctc = 0x0A;
	return ctc;
}

- (unsigned char)fromASCII:(unsigned char)ctc
{
	if (ctc >= 'A' && ctc <= 'Z') ctc += 153;
	if (ctc >= '0' && ctc <= '9') ctc += 160;
	if (ctc == '?') ctc = 0x34;
	if (ctc == '!') ctc = 0x36;
	if (ctc == ',') ctc = 0x9C;
	if (ctc == '.') ctc = 0xCF;
	if (ctc == ' ') ctc = 0xF4;
	if (ctc == '-') ctc = 0xF6;
	if (ctc == 0x0A) ctc = 0xFD;
	return ctc;
}

- (int)browser:(NSBrowser *)br numberOfRowsInColumn:(int)col
{
	if (col == 0)
		return [textStrings count];
	else
		return [[[textStrings objectAtIndex:[br selectedRowInColumn:0]] objectForKey:@"List"] count];
}

- (void)browser:(NSBrowser *)br willDisplayCell:(id)cell atRow:(int)row column:(int)col
{
	NSString *section;
	NSArray *fc;
	
	if (col == 0) {
		
		section = [[textStrings objectAtIndex:row] objectForKey:@"Name"];
		[cell setStringValue:section];
		[cell setLeaf:NO];
		
	} else {
		
		fc = [[textStrings objectAtIndex:[br selectedRowInColumn:0]] objectForKey:@"List"];
		NSString *str = [fc objectAtIndex:row];
		[cell setStringValue:str];
		[cell setLeaf:YES];
		
	}
}

- (int)numberOfVisibleColumns
{
	return 1;
}

// Note : levels in the level-up menu must reflect the changes

// NEXT      1BE5
// ATTACK    1BF9
// MAGIC     1C07
// LIFE      1C15
// UP        1C1E
// CANCEL    1C23
// WILL      1D49
// GO UP     1D57

- (void)controlTextDidChange:(NSNotification *)notif
{
	id fe = [[notif userInfo] objectForKey:@"NSFieldEditor"];
	id mt = [[fe superview] superview];
	int s = [mt tag];
	
	if ([[fe string] length] > s) {
		NSBeep();
		[fe setTextColor:[NSColor redColor]];
		canSave = NO;
	} else {
		[fe setTextColor:[NSColor blackColor]];
		canSave = YES;
	}
}

@end

// NSArray *arr = [NSColorList availableColorLists];
// NSColorList *clist = [arr objectAtIndex:0];
// [clist writeToFile:@"/Users/sim/Desktop/clist.clr"];


