//
//  ApplicationController.m
//  ZIA Gallery Maker
//
//  Created by Frank Mcpherson on 12/24/09.
//  Copyright 2009 bitdoctors.com. All rights reserved.
//

#import "ApplicationController.h"
#import "ImageFilter.h"
#import "BWSnippetKeeper.h"
#import "BWThumbnailHTMLAccumulator.h"
#import "Artwork.h"


@implementation ApplicationController

@synthesize imageCount;
@synthesize imageIndex;
@synthesize galleryTitle;
@synthesize progressPanelTitle;

- (id)init
{
	self = [super init];
	if (self) 
	{
		snippets = [[BWSnippetKeeper alloc] init];
	}
	return self;
}

- (void)dealloc 
{
	[snippets release];
	
	[super dealloc];
}



- (IBAction)writeGallery:(id)sender
{
	NSOpenPanel *panel;
	NSString *newPath = nil;
	
	// Get the path where we want to write the gallery
	panel = [NSOpenPanel openPanel];
	[panel setTitle:@"Choose or create a directory for new gallery"];
	[panel setCanCreateDirectories:YES];
	[panel setCanChooseFiles:NO];
	[panel setCanChooseDirectories:YES];
	[panel setAllowsMultipleSelection:NO];
	if ([panel runModalForTypes:nil] == NSOKButton) {
		if ([[panel filenames] count] == 1) 
		{
			newPath = [[panel filenames] lastObject];
		}
	}
	
	if (newPath != nil) {
		// Destination directory should be empty 
		NSArray *directoryContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:newPath error:nil];
		if ([directoryContents count] > 0) {
			NSString *alert = [NSString stringWithFormat:@"Directory \'%@\' is not empty", newPath];
			NSAlert *tooManyFiles = [NSAlert alertWithMessageText:alert
													defaultButton:nil
												  alternateButton:nil
													  otherButton:nil
										informativeTextWithFormat:@"Please choose an empty directory, or create a new directory, to hold the new Gallery"];
			[tooManyFiles runModal];
		} else 
		{
			outPath = [newPath retain];
			thumbnailDimension = [[NSUserDefaults standardUserDefaults] integerForKey:@"thumbnailDimension"];
			enlargementDimension = [[NSUserDefaults standardUserDefaults] integerForKey:@"imageDimension"];
			// First display a progress sheet
			[NSApp beginSheet:sheet modalForWindow:[self window]
				modalDelegate:self didEndSelector:NULL contextInfo:nil];
			
			// Now detach a new thread to perform the image filtering
			[NSThread detachNewThreadSelector:@selector(processImagesWorker) toTarget:self withObject:nil];
			
		}
	}
}


- (void)processArtworks:(NSArray *)artworks 
			  forRect:(CGRect)targetRect 
			  withTag:(NSString *)fileTag 
  withBackgroundColor:(NSColor *)color
{
	// Prepare the image filter
	ImageFilter *filter = [[ImageFilter alloc] initWithTargetSize:targetRect backgroundColor:color];
	
	CIImage *inImage;
	NSString *filePath;
		
	[self willChangeValueForKey:@"imageIndex"];
	for (Artwork *artwork in artworks) 
	{
		filePath = [artwork imageRepresentation];
		inImage = [CIImage imageWithContentsOfURL:
				   [NSURL fileURLWithPath:filePath]];
		[filter saveImage:[filter filterImage:inImage]
				   toFile:[NSString stringWithFormat:@"%@/%@%@.jpg", outPath, fileTag, [artwork inventoryCode]]];
		[self willChangeValueForKey:@"imageIndex"];
		imageIndex++;
		[self didChangeValueForKey:@"imageIndex"];

	}	
	// Release the filter
	[filter release];
}

// This runs on a separate thread from the app event loop so we don't show
// the pizza wheel. Call processImages:withTag:withBackgroundColor: for
// each of our image sizes. 
- (void)processImagesWorker {
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	NSArray *artworks = [artworkArrayController arrangedObjects];
		
	// Notify bindings we've changed the image count so the progress bar can work
	[self willChangeValueForKey:@"imageCount"];
	imageCount = [artworks count] * 2;
	[self didChangeValueForKey:@"imageCount"];
	[self willChangeValueForKey:@"imageIndex"];
	imageIndex = 0;
	[self didChangeValueForKey:@"imageIndex"];
	
	// Add the color well by passing in the color here
	
	[self processArtworks:artworks 
				  forRect:CGRectMake(0.0f, 0.0f, thumbnailDimension, thumbnailDimension)
				  withTag:@"thumb_"
	  withBackgroundColor:[self colorFromDefaultsForKey:@"thumbnailBackgroundColor"]];
	[self processArtworks:artworks
				  forRect:CGRectMake(0.0f, 0.0f, enlargementDimension, enlargementDimension)
				  withTag:@""
	  withBackgroundColor:[self colorFromDefaultsForKey:@"imageBackgroundColor"]];
	
	// Make an accumulator to do hold the gallery HTML. 
	BWThumbnailHTMLAccumulator *html = [BWThumbnailHTMLAccumulator accumulatorWithSnippets:snippets];
	[html addHeaderWithTitle:galleryTitle];
	[html addSnippetWithKey:@"snippetGalleryHeader"];
	[html addArbitraryHTML:[NSString stringWithFormat:@"<h1 align=center id=\"gallerytitle\">%@ Gallery</h1>", galleryTitle]];
	[html addBeforeThumbnails];
	// TODO FHM This needs to be styled like the existing galleries
	NSSize size;
	size.height = size.width = thumbnailDimension;
	// Right now I'm just adding the thumbnails
	NSString *enlargementFilename;
	for (Artwork *aWork in artworks) 
	{
		enlargementFilename = [self writeArtwork:aWork toPath:outPath withParentPage:@"index.html"];
		[html addEnlargementNamed:enlargementFilename 
			 thumbnailNamed:[NSString stringWithFormat:@"%@%@.jpg", @"thumb_", [aWork inventoryCode]]
					   size:size];
	}
	[html addAfterThumbnails];
	[html addSnippetWithKey:@"snippetGalleryFooter"];
	[html writeToFile:[outPath stringByAppendingString:@"/index.html"]];
	
	NSTask *chmod = [[NSTask alloc] init];
	[chmod setCurrentDirectoryPath:outPath];
	[chmod setLaunchPath:[[NSBundle mainBundle] pathForResource:@"AddExecuteFilePermissions" ofType:@"sh"]];
	[chmod launch];
	[chmod waitUntilExit];
	[chmod autorelease];
																				   
	[sheet orderOut:nil];
	[NSApp endSheet:sheet];
	[pool release];
	
}

- (NSColor *)colorFromDefaultsForKey:(NSString *)aKey
{
    NSColor *theColor=nil;
    NSData *theData=[[NSUserDefaults standardUserDefaults] dataForKey:aKey];
    if (theData != nil)
        theColor=(NSColor *)[NSUnarchiver unarchiveObjectWithData:theData];
    return theColor;
}

- (NSString *)progressPanelTitle
{
	return [NSString stringWithFormat:@"Writing %@", galleryTitle];
}

- (NSString *)writeArtwork:(Artwork *)artwork
			  toPath:(NSString *)path 
	  withParentPage:(NSString *)parentPage
{
	BWThumbnailHTMLAccumulator *html = [BWThumbnailHTMLAccumulator accumulatorWithSnippets:snippets];
	NSString *enlargementFilename = [NSString stringWithFormat:@"enlarge_%@.html", [artwork inventoryCode]];
	NSString *imageFilename = [NSString stringWithFormat:@"%@.jpg",[artwork inventoryCode]];
	NSString *tableStart = [NSString stringWithFormat:@"<table width=\"720\" border=\"0\" align=\"center\" cellpadding=\"2\" cellspacing=\"20\">\n<tr>\n<th width=\"%d\" height=\"%d\" scope=\"col\">", enlargementDimension, enlargementDimension];
	NSString *imgString = [NSString 
						   stringWithFormat:@"<img id=\"enlargement_image\" src='%@' width='%d' height='%d' alt='Artwork Image'>\n</th>",imageFilename, enlargementDimension, enlargementDimension];
	NSString *artData = [NSString stringWithFormat:@"<th id=\"enlargement_data\" width=\"310\" scope=\"col\">\n<p><em>%@</em></p>\n<p class=\"bigger\">%@</p>\n<p>%@</p>\n<p>%@</p>\n<p>%@</p>\n<p>%@</p>\n<p>Item # %@</p></th></tr></table>",
						 [artwork westernTitle],
						 [artwork chineseTitle],
						 [artwork script],
						 [artwork size],
						 [artwork medium],
						 [artwork cost],
						 [artwork inventoryCode]];
	[html addHeaderWithTitle:[artwork westernTitle]];
	[html addArbitraryHTML:@"<p>&nbsp</p><div id=\"container\"><p>&nbsp</p>"];
	[html addArbitraryHTML:tableStart];
	[html addArbitraryHTML:imgString];
	[html addArbitraryHTML:artData];
	[html addArbitraryHTML:@"<p><a href=\"index.html\">Return</a></p>"];
	[html addGalleryFooter];
	[html writeToFile:[outPath stringByAppendingString:[NSString stringWithFormat:@"/%@",enlargementFilename]]];
	// TODO FHM Set permissions to +x so includes work
	return enlargementFilename;
}

@end
