#import <appkit/appkit.h>
#import "Document.h"
#import "TextController.h"

// this class is responsible for managing
// the savepanel and openpanel
// it is also responsible for responding
// to remote messages from the Workspace

@implementation TextController

// automatically sent after the .nib file
// has finished loading
- awakeFromNib
{
	// using the new method first creates
	// the objects; since there is only one
	// openpanel and savepanel per application,
	// subsequent invocations return the
	// existing savepanel and openpanel,
	// as appropriate
	id savePanel = [SavePanel new];
	id openPanel = [OpenPanel new];
	// by default, an openpanel only allows
	// one file to be opened
	[openPanel allowMultipleFiles:YES];
	return self;
}

// create a new document in response
// to the New menu option
- newDocument:sender
{
	id document = [[Document alloc] init];
	[document showDocument];
	[[document window] setTitle:UNTITLED];
	return self;
}

// open the document in response to
// the Open menu option
- showOpenPanel:sender
{
	const char *file, *directory;
	const char *const *filenames;
	static const char
		*const wordTypes[] = {FILE_EXTENSION, NULL};
	char fullPathName[MAXPATHLEN];
	id openPanel = [OpenPanel new];

	// ensure that the openpanel allows multiple
	// files to be selected
	[openPanel allowMultipleFiles:YES];
	// display only files with "word" extension
	if ([openPanel runModalForTypes:wordTypes])
		{
		// get list of filename(s) selected
		// the filenames method returns a
		// a pointer to all the strings
		filenames = [openPanel filenames];
		// get directory first
		directory = [openPanel directory];
		do
			{
			// get filename
			file = *(filenames++);
			// construct entire pathname
			strcpy(fullPathName, directory);
			// append directory to filename
			strcat(fullPathName, "/");
			strcat(fullPathName, file);
			[[Document alloc]
				initDocumentFromFile:fullPathName];
			}
		while (*(filenames) != NULL);
	    	}
	return self;
}

// save the document in response to
// the Save menu option
- showSavePanel:sender
{
	const char *wordType = FILE_EXTENSION;
	const char *fullPathName, *title;
	id document = [[NXApp mainWindow] delegate];
	id savePanel = [SavePanel new];

	// make sure there is a document first
	if (document)
		{
		// if document has not been saved
		// then present savepanel to get filename
		title = [[document window] title];
		if (strcmp(title, UNTITLED) == 0)
			{
			[savePanel setRequiredFileType:wordType];
			if ([savePanel runModal])
				{
				fullPathName = [savePanel filename];
				return [document saveDocumentToFile:
					fullPathName];
				}
			else
				return nil;
			}
		// else just save the file
		else
			return [document saveDocumentToFile:title];
		}
	return self;
}

@end
