#import "tableDataSource.h"
#import "arrayBSorter.h"
#import "fontWindow.h"

@implementation tableDataSource
- (void) awakeFromNib
    {	
		/* Def font size */
		size = 14;
		
		/* NSTable view store*/
		tableData = [NSMutableDictionary new];
		
		// Array for the strings
        stringFont = [[[NSMutableArray alloc]init]retain];
		
		/* Retrieving font family list  */
		allFonts = [[[NSFontManager sharedFontManager] availableFontFamilies]retain];
		// ricorda availableMembersOfFontFamily:
		
		[infoField setStringValue:[NSString stringWithFormat:@"Found %d fonts.", [allFonts count]]];
		
		sorter = [[arrayBSorter alloc]init];
		
        [tableView setTarget:self];
        [tableView setDoubleAction:@selector(detachFont:)];
        //[tableView setAction:@selector(detachFont:)];
		//NSLog(@"Collection %@", [[NSFontManager sharedFontManager] collectionNames]);
		//NSLog(@"Collection %@", [[NSFontManager sharedFontManager] fontDescriptorsInCollection:@"Web"]);

}

- (void) detachFont:(id)sender{
    NSLog(@"%@", sender);
    fontWindow *fw = [[fontWindow alloc] initWithContentRect:NSMakeRect(100,100,300,300) 
                                                    styleMask: NSBorderlessWindowMask 
                                                    backing:NSBackingStoreBuffered 
                                                    defer:NO];
    [fw makeKeyAndOrderFront:self];
}

#pragma mark Interface Builder Method

- (IBAction)loadData:(id)sender{
		unsigned fontCounter = [allFonts count];
		NSMutableDictionary *d = [NSMutableDictionary dictionary];
				
		int i = 0;
		for (i; i < fontCounter; ++i) {
			/*Creating string object with font*/
			[d setObject:[NSFont fontWithName:[allFonts objectAtIndex:i] size:size] forKey:NSFontAttributeName];
			NSMutableAttributedString *tmpString = [[NSMutableAttributedString alloc] initWithString:@"The quick brown fox jumps over the lazy dog" attributes:d];
			/*Populating string array*/
			[stringFont addObject:tmpString];
		}
		
		// Sorting font _SLOOOW_
		//stringFont = [sorter BSort:stringFont size:[stringFont count]]; 
		
		// Per cambiare gli attributi delle stringhe devo usare le NSMutableAttributedString
		[tableData setObject:stringFont forKey:@"font"];

		/* Reloading table data*/
		[tableView reloadData];
}

-(IBAction)sortData:(id)sender{
	if([[sender label] isEqualToString:@"Sort by W"]){
		stringFont = [sorter BSort:stringFont size:[stringFont count] sortBy:0];
	}
	else if ([[sender label] isEqualToString:@"Sort by H"]){
		stringFont = [sorter BSort:stringFont size:[stringFont count] sortBy:1];

	}
		[tableView reloadData];

}

- (IBAction)changeSize:(id)sender{
	float tsize = [[sender stringValue]floatValue];
	if(tsize == 0) tsize = 14;
	unsigned fontCounter = [allFonts count];
	//NSMutableDictionary *atr = [NSMutableDictionary dictionary];

	int i = 0;
	for (i; i < fontCounter; ++i) {
		//[atr setObject:[NSFont fontWithName:[allFonts objectAtIndex:i] size:tsize] forKey:NSFontAttributeName];
		//[[stringFont objectAtIndex:i] setAttributes:atr range:NSMakeRange(0, [[stringFont objectAtIndex:1] length])];
        
        [[stringFont objectAtIndex:i] addAttribute:NSFontAttributeName
                                      value: [NSFont fontWithName:[allFonts objectAtIndex:i] size:tsize]
                                      range:NSMakeRange(0, [[stringFont objectAtIndex:1] length])];
        //NSMutableAttributedString *tmpString = [[NSMutableAttributedString alloc] initWithString:@"Reverse" attributes:atr];

        //[[stringFont objectAtIndex:i] setAttributedString:tmpString];
		}
	//[tableData setObject:stringFont forKey:@"font"];
	[tableView reloadData];
}

- (IBAction)changeText:(id)sender{
	NSString* text = [sender stringValue];

    if([text isEqualToString:@""]){
        text = @"The quick brown fox jumps over the lazy dog";
    }

	unsigned fontCounter = [allFonts count];
	NSDictionary *atr = [NSDictionary dictionary];

	int i = 0;
	for (i; i < fontCounter; ++i) {
        //NSSize fontSize = [[stringFont objectAtIndex:i]size];
        
        /*
        NSFont* tmpFont = [[[stringFont objectAtIndex:i] attributesAtIndex:0 effectiveRange:nil]objectForKey:NSFontAttributeName];

		[atr setObject:[NSFont fontWithName:[allFonts objectAtIndex:i] size:[tmpFont pointSize]] forKey:NSFontAttributeName];
		//[[stringFont objectAtIndex:i] setAttributes:atr range:NSMakeRange(0, [[stringFont objectAtIndex:1] length])];
        
        NSMutableAttributedString *tmpString = [[NSMutableAttributedString alloc] initWithString:text attributes:atr];

        [[stringFont objectAtIndex:i] setAttributedString:tmpString];
        [[stringFont objectAtIndex:i] deleteCharactersInRange:NSMakeRange(0, [[stringFont objectAtIndex:1] length])]
        */
        atr = [[stringFont objectAtIndex:i] attributesAtIndex:0 effectiveRange:NULL];
        NSMutableAttributedString *tmpString = [[NSMutableAttributedString alloc] initWithString:text attributes:atr];
        [[stringFont objectAtIndex:i] setAttributedString:tmpString];
		}
	[tableData setObject:stringFont forKey:@"font"];
	[tableView reloadData];
}

- (IBAction)changeTableBackground:(id)sender{
    NSColor* c = [sender color];
    [tableView setBackgroundColor:c];
}

- (IBAction)changeTextColor:(id)sender{               
	unsigned fontCounter = [allFonts count];

	int i = 0;
	for (i; i < fontCounter; ++i) {
		[[stringFont objectAtIndex:i] addAttribute:NSForegroundColorAttributeName
                                      value:[sender color]
                                      range:NSMakeRange(0, [[stringFont objectAtIndex:1] length])];
        
        //NSMutableAttributedString *tmpString = [[NSMutableAttributedString alloc] initWithString:@"Reverse" attributes:atr];

        //[[stringFont objectAtIndex:i] setAttributedString:tmpString];
		}
	[tableData setObject:stringFont forKey:@"font"];
	[tableView reloadData];

               
}

#pragma mark Tableview Data Source Method

/* Data source Method */

- (id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)row
{
        return [[tableData objectForKey:[tableColumn identifier]] objectAtIndex:row];

}

- (int)numberOfRowsInTableView:(NSTableView *)aTableView
{
        return [[tableData objectForKey:@"font"] count];

}

/* End Data Source Method */


#pragma mark Tableview Delegate Method

/* Delegate Method */

- (float)tableView:(NSTableView *)aTable heightOfRow:(int)aRow{
    //NSRect tRect= [tableView bounds];
    
    // Vittoria per le righe alte quanto voglio
	NSSize t = [[stringFont objectAtIndex:aRow] size];
    //if(tRect.size.width >= t.width){
        return t.height + 8;
    /*}
    else{
        return (t.height)*2;
    }*/
}


- (NSString *)tableView:(NSTableView *)tv toolTipForCell:(NSCell *)cell rect:(NSRectPointer)rect tableColumn:(NSTableColumn *)tc row:(int)row mouseLocation:(NSPoint)mouseLocation {
	NSFont* currFont = [[[stringFont objectAtIndex:row] attributesAtIndex:0 effectiveRange:nil]objectForKey:NSFontAttributeName];
	NSString* toolTip = [[NSString alloc] initWithString:[currFont familyName]];
	toolTip = [toolTip stringByAppendingString:[NSString stringWithFormat:@" %dpt.", (int)[currFont pointSize]]];
	//NSRange r = [toolTips rangeOfString:@"pt."];
	//NSLog(@"%d, %d", (r.length, r.location));
	return toolTip;
}

/* End Delegate Method*/

@end
