#import "AppController.h"
#import "MyDocument.h"

@implementation AppController

- (IBAction)checkForUpdates:(id)sender
{
	// update checks removed, don't work anyway
}

- (IBAction)deleteProject:(id)sender
{
	NSString* projectFile;
	NSString* projectFullPath;
	projectFile = [[projListController selection] valueForKeyPath: @"fileName"];	
	projectFullPath = [[[NSUserDefaults standardUserDefaults] stringForKey: @"ProjectFolder"] stringByAppendingPathComponent: projectFile];
	
	if ([[NSAlert alertWithMessageText:NSLocalizedString(@"Delete project",@"[2]")
						 defaultButton:NSLocalizedString(@"Yes",@"[2]")
					   alternateButton:NSLocalizedString(@"No",@"[2]")
						   otherButton:nil
			 informativeTextWithFormat:NSLocalizedString(@"You are about to delete the project %@ permanently. Do you confirm?",@"[2]"),projectFullPath] 
		runModal] == NSAlertAlternateReturn)
		return;

	NSFileManager* fm = [NSFileManager defaultManager];

	if (![fm removeFileAtPath: projectFullPath handler: nil])
	{
		[[NSAlert alertWithMessageText: NSLocalizedString(@"Error", @"[1]")
						 defaultButton: NSLocalizedString(@"OK", @"[1]")
					   alternateButton: nil
						   otherButton: nil
			 informativeTextWithFormat: NSLocalizedString(@"synXer was not able to delete the project file %@.",@"[1]"),
			projectFullPath] 
			runModal];
	}
	else
	{
		[self rescanFolder: self];
	}
}

- (IBAction)openProject:(id)sender
{
	NSString* projectFile;
	NSString* projectFullPath;
	
	projectFile = [[projListController selection] valueForKeyPath: @"fileName"];	
	projectFullPath = [[[NSUserDefaults standardUserDefaults] stringForKey: @"ProjectFolder"] stringByAppendingPathComponent: projectFile];
	NSURL* projectURL = [NSURL fileURLWithPath: projectFullPath];
	[[NSDocumentController sharedDocumentController] openDocumentWithContentsOfURL: projectURL
																		   display: YES
																			 error: nil];
}

- (IBAction)showHideProjectList:(id)sender
{
	if ([projectsWindow isVisible])
	{
		[projectsWindow orderOut: self];
	}
	else
	{
		[projectsWindow makeKeyAndOrderFront: self];
	}
}

- (IBAction)rescanFolder:(id)sender
{
	// Remember the selected row in the table view
	int row = [projectsTable selectedRow];
	
	// Show the panel and start spinning the indicator
	[scanningPanel makeKeyAndOrderFront: self];
	[scanningIndicator startAnimation: self];
	
	// Get the location of the project folder
	NSString* folder;
	folder = [[NSUserDefaults standardUserDefaults] stringForKey: @"ProjectFolder"];
	
	// Check if the folder exists, if not - create it
	NSFileManager* fm = [NSFileManager defaultManager];
	BOOL isDir = NO;
	BOOL exists;
	exists = [fm fileExistsAtPath: folder isDirectory: &isDir];
	if (! exists)
	{
		if ([[NSAlert alertWithMessageText: NSLocalizedString(@"Creating project folder",@"[1]")
							 defaultButton: NSLocalizedString(@"OK",@"[1]") 
						   alternateButton: NSLocalizedString(@"Cancel",@"[1]") 
							   otherButton: nil 
				 informativeTextWithFormat: NSLocalizedString(@"synXer will create a new folder %@, in which all your projects will be stored by default. You can change the location of the project folder later, in the synXer preferences.",@"[1]"),
										    folder
			] runModal] == NSAlertDefaultReturn)
		{
			[[NSFileManager defaultManager] createDirectoryAtPath: folder attributes: nil];			
		}
	}
	else if (exists && ! isDir)
	{
		[[NSAlert alertWithMessageText: NSLocalizedString(@"Invalid project folder",@"[1]")
						 defaultButton: NSLocalizedString(@"OK",@"[1]") 
					   alternateButton: nil 
						   otherButton: nil 
			 informativeTextWithFormat: NSLocalizedString(@"The project folder %@ is not a directory. Please choose another folder for your projects in the synXer preferences.",@"[1]"),
										folder
			] runModal];		
	}
	
	
	// Scan the folder for .synxer files
	NSMutableArray* newProjList;
	newProjList = [[NSMutableArray alloc] init];
	NSDirectoryEnumerator* folderContents;
	NSString* fileName;
	
	folderContents = [fm enumeratorAtPath: folder];
	while (fileName = [folderContents nextObject])
	{
		NSString* extension = [fileName pathExtension];
		if ([extension isEqualToString:@"synxer"])
		{
			NS_DURING
				id contents;
				contents = [NSKeyedUnarchiver unarchiveObjectWithFile: [folder stringByAppendingPathComponent: fileName]];
				if ([contents isKindOfClass: [NSMutableDictionary class]])
				{
					[contents setObject: fileName forKey: @"fileName"];
					[newProjList addObject: contents];
				}
				NS_HANDLER
					// nothing to do here - invalid files will not be treated as projects
				NS_ENDHANDLER					
		}
	}
		
	// Set the file list
	// We use KVO to inform all interested that projList has changed
	[self setValue: newProjList forKey: @"projList"];
	[projListController setContent: [self projList]];
	[newProjList release];
	[projectsTable selectRow:row byExtendingSelection:NO];
		
	// Update the array
	// No need - KVO above did all the work.
	
	// Stop the animation and hide the panel
	[scanningIndicator stopAnimation: self];
	[scanningPanel orderOut: self];
}

- (IBAction)preferences:(id)sender
{
	if (!preferencesPanel)
	{
		[NSBundle loadNibNamed:@"PreferencesPanel" owner:self];
	}
	[preferencesPanel makeKeyAndOrderFront:self];
}

- (IBAction)projectListDoubleClicked:(id)sender
{
	[self openProject: sender];
}

- (IBAction)chooseDefaultFolder:(id)sender
{
	NSString* chosenFolder = [MyDocument selectFolder];
	if (chosenFolder)
		[[NSUserDefaults standardUserDefaults] setValue:chosenFolder forKey:@"ProjectFolder"];
}


- (NSMutableArray*) projList
{
	return projList;
}

- (void) setProjList: (NSMutableArray*) newProjList
{
	if (projList != newProjList)
	{
		[newProjList retain];
		if (projList)
			[projList autorelease];
		projList = newProjList;
	}
}

// The application should not open untitled document at start
- (BOOL) applicationShouldOpenUntitledFile: (NSApplication*) sender
{
	return NO;
}

- (void) projectSavedNotificationHandler: (NSNotification*) n
{
	[self rescanFolder: self];
}

- (void) applicationDidFinishLaunching: (NSNotification*) n
{
	[self rescanFolder: self];
	[self showHideProjectList: self];
	[[NSNotificationCenter defaultCenter] addObserver: self
											 selector: @selector(projectSavedNotificationHandler:)
												 name: @"SXProjectSaved"
											   object: nil];
	[projectsTable setDoubleAction: @selector(projectListDoubleClicked:)];
	[projectsTable setTarget: self];	
}

+ (void) registerFactoryDefaults
{
	NSMutableDictionary* factoryDefaults;
	factoryDefaults = [NSMutableDictionary dictionary];
	NSString* defFolder = [NSHomeDirectory() stringByAppendingPathComponent: @"Documents/synXer"];
	[factoryDefaults setObject: defFolder forKey: @"ProjectFolder"];
	[factoryDefaults setObject:[NSNumber numberWithFloat:1.0] forKey:@"ComparisonTolerance"];
	[factoryDefaults setObject:[NSNumber numberWithBool:YES] forKey:@"OverwriteLocked"];
	[[NSUserDefaults standardUserDefaults] registerDefaults: factoryDefaults];	
	[[NSUserDefaultsController sharedUserDefaultsController] setInitialValues: factoryDefaults];
}

// Global initialization
// Sets the factory defaults
+ (void) initialize
{
	[self registerFactoryDefaults];
}

- (NSArray*) availableModes
{
	return [MyDocument availableModes];
}

- (void) dealloc
{
	[[NSNotificationCenter defaultCenter] removeObserver: self];
	if (projList)
		[projList release];
	[super dealloc];
}

@end
