//  Created by Joe Becker on 3/7/05.
//  Copyright 2005 __MyCompanyName__. All rights reserved.

#import "Controller.h"
#import "GraphView.h"
#import "ZoomScrollView.h"


@implementation Controller

- (GraphView *)graphView
{
	return graphView;
}

- (GmtShipTrack *)gmtShipTrack
{
	return gmtShipTrack;
}

- (id)setGmtShipTrack:(GmtShipTrack *)track
{
       gmtShipTrack = track;
	return self;
}


- (id)navController
{
	return navController;
}

- (id)dataController
{
	return dataController;
}

- (id)statController
{
	return statController;
}

- (IBAction)showPrefs:(id)sender
{
       if (!prefController) {
              [NSBundle loadNibNamed:@"Preferences.nib" owner:self];
       }
       [ [prefController window] makeKeyAndOrderFront:sender];
}


- (void)openDocument:(id)sender
{
       int result;	
       NSArray *fileTypes = [NSArray arrayWithObject:@"cm"];
      
	oPanel = [NSOpenPanel openPanel];
       [oPanel setAllowsMultipleSelection:NO];
       result = [oPanel runModalForDirectory:nil file:nil types:fileTypes];
	
       if (result == NSOKButton) {
              NSArray *filesToOpen = [oPanel filenames];
              NSString *tmp;
              for (tmp in filesToOpen) {
			[gmtShipTrack dealloc];
			gmtShipTrack = [[GmtShipTrack alloc] init];	// released ??? BUT NOT autorelease here
			[gmtShipTrack readFromPath:tmp];
                     aFile = tmp;
              }
	}
	return; //FIXME: premature exitulation skip the jpeg
	
	NSBundle * bundle = [[NSBundle bundleForClass:[self class]] autorelease];
	
	// Now find the image:
	
	NSString * path = [bundle pathForResource:@"lame" ofType:@"jpg"];
	
	//Load the image:
	
	NSImage * image = [[[NSImage alloc] initWithContentsOfFile: path] autorelease];
	
	// Scale the image:
	
	[image setSize:NSMakeSize (100, 50)];
	
	
	//Draw the image:
	
	[image compositeToPoint:NSMakePoint(20,30) operation:NSCompositeSourceOver];
	
}



// This implementation works around an AppKit bug in Cocoa 10.1
//   by placing the view in a different window and asking that
//   window to create the PDF for the view.

- (NSData *)PDFForView:(NSView *)aView
{
       NSRect frame         = [aView frame];
       NSView *oldSuperview = [aView superview];
       NSWindow *tempWindow;
       NSData *pdf;
	
       tempWindow = [[NSWindow alloc]
                     initWithContentRect:frame
                     styleMask:0
                     backing:NSBackingStoreRetained
                     defer:NO];
	
       [[tempWindow contentView] addSubview:aView];
       pdf = [tempWindow dataWithPDFInsideRect:[tempWindow frame]];
       [oldSuperview addSubview:aView];
       return pdf;
}


- (NSData *)TIFFForView:(NSView *)aView
{
       NSImage *image = [[NSImage alloc] 
                         initWithData:[self PDFForView:aView]];
	
       [image autorelease];
       return [image TIFFRepresentation];
}



- (IBAction)setFormat:(id)sender
{
       [sPanel
        setRequiredFileType:
        [ [[sender selectedCell] title] lowercaseString] ];
}


// This next one is way broken, not real clear why we needed such a mess...
- (void)savePanelDidEnd:(NSSavePanel *)sheet
             returnCode:(int)returnCode
            contextInfo:(void  *)contextInfo
{
       NSData *image=0;
       NSString *filetype = [sheet requiredFileType];
	
       if (returnCode==0) return;    // User did not click OK
	
       if ([filetype isEqualToString:@"pdf"]) {
              image = [self PDFForView:graphView];
       }
       if ([filetype isEqualToString:@"tiff"]) {
              image = [self TIFFForView:graphView];
       }
       if (image==0) {
              NSRunAlertPanel(nil,@"Unknown file type '%@'",
                              nil,nil,nil,filetype);
              return;
       }
	
       if ([image writeToFile:[sheet filename] atomically:NO]==NO) {
              NSRunAlertPanel(nil,
                              @"Cannot save file '%@': %s",nil,nil,nil,
                              [sheet filename],
                              strerror(errno));
       }
}

- (IBAction)saveDocumentTo:(id)sender
{
       NSString    *fileTypes = @"cm";
	
       // Get a Save Panel
       sPanel  = [NSSavePanel savePanel];
       [sPanel setTitle:@"Save GMT data"];
	
       // Set the required file type
       [sPanel setRequiredFileType: fileTypes];
	[sPanel setCanCreateDirectories:YES];
	
	int result = [sPanel runModalForDirectory:nil file:[aFile lastPathComponent]];
	
       if (result == NSOKButton) {
		aFile = [sPanel filename];
		[gmtShipTrack writeToPath:aFile];
		[[navController graphView] setFormula:aFile];
		[[dataController graphView] setFormula:aFile];
		[[statController graphView] setFormula:aFile];
	}
}

// Chapter 20

- (void)copyToPasteboard:(NSPasteboard *)pboard
{
       // Declare that we can handle PDF and TIFF
       [pboard declareTypes:[NSArray arrayWithObjects:
                             NSPDFPboardType,NSTIFFPboardType,nil] owner:self];
	
       // Now put a PDF on the pasteboard
       [pboard setData:[self PDFForView:graphView]
               forType:NSPDFPboardType];
}


- (IBAction)pb_copy:(id)sender
{
       [self copyToPasteboard: [NSPasteboard generalPasteboard] ];
}



- (void)pasteboard:(NSPasteboard *)sender
provideDataForType:(NSString *)type
{
       if ([type isEqualToString:NSTIFFPboardType]) {
              NSImage *image  = [[NSImage alloc]
                                 initWithData:[sender dataForType:NSPDFPboardType]];
		
              [sender setData:[image TIFFRepresentation]
                      forType:NSTIFFPboardType];
       }
}


// Services

- (void)applicationDidFinishLaunching:(NSNotification *)aNot
{
       NSLog(@"Registering as a Services Provider");
       [NSApp setServicesProvider:self];
}



- (void)graphFormula:(NSPasteboard *)pboard
            userData:(NSString *)userData
               error:(NSString **)error
{
       BOOL wasHidden = [NSApp isHidden];
	
       [pboard types];                     // get the types
       [graphView setRunningAsService:YES];
       [graphView setFormula:
        [pboard stringForType:NSStringPboardType]];
       [graphView graph:nil];              // do the graph
	
       // The NSEvent will cause periodic events to flow so that
       //   the window will pick up events form the NSTask.
       // This may be a bug in the AppKit.
       [NSEvent startPeriodicEventsAfterDelay:0 withPeriod:0.1];
       [NSApp runModalForWindow:[graphView window]];
       [NSEvent stopPeriodicEvents];
	
       [graphView setRunningAsService:NO];
       [self copyToPasteboard:pboard ];
	
       if (wasHidden) {
              [NSApp hide:self];
       }
}



// Chapter 21 - Defaults

- (void)awakeFromNib
{
       [[graphView window]  setFrameUsingName:@"Main Window"];
       [[graphView window]  setFrameAutosaveName:@"Main Window"];
	
	gmtShipTrack = [[GmtShipTrack alloc] init];
	[navController  setGmtShipTrack:gmtShipTrack];
	[dataController setGmtShipTrack:gmtShipTrack];
	[statController setGmtShipTrack:gmtShipTrack];
}




@synthesize prefController;
@synthesize dataController;
@synthesize statController;
@synthesize oPanel;
@synthesize aFile;
@synthesize navController;
@synthesize sPanel;
@synthesize formatMatrix;
@synthesize formatBox;
@end
