#import "PDFConverter.h"
#import "NSTask+utils.h"

@implementation PDFConverter

- init
{
        [NSApp setDelegate:self];
        return self;
}

- (BOOL)application:(NSApplication *)sender openFile:(NSString *)filename 
{
        [inputFileName setStringValue:filename];
        [outputFileName setStringValue:@"/tmp/foo.ps"];

        [self convert:self];
        
    	return YES;
}

- (void)awakeFromNib
{
        [userMessage setStringValue:@""];
}


- (void)convert:(id)sender
{
    	NSMutableString	*taskString = [NSMutableString string];
   	NSTask *aTask;
    	NSMutableArray *args;

    
    	aTask = [[[NSTask alloc] init] autorelease];
    
    	[aTask setCurrentDirectoryPath:[[NSBundle mainBundle] resourcePath]];
        [taskString appendString:[[NSBundle mainBundle] resourcePath]];
        
    	if ([convertToPS state]) {
        	[taskString appendString:@"/pdftops"];
    	} else {
                [taskString appendString:@"/pdftotext"];
        }
        
    	[aTask setLaunchPath:taskString];

        if (![[inputFileName stringValue] length]) {
                [userMessage setStringValue:@"No input file specified"];
                return;
        }
	if (![[outputFileName stringValue] length]) {
                [userMessage setStringValue:@"No output file specified"];
                return;
        }


        args = [NSMutableArray arrayWithObjects:[inputFileName stringValue], [outputFileName stringValue], nil];
        [aTask setArguments:args];
        [aTask launch];
        [aTask waitUntilExit];
	
	[userMessage setStringValue:@"Conversion complete"];

	if ([openFileAfterConversion state]) {
                [[NSWorkspace sharedWorkspace]openFile:[outputFileName stringValue]];
        }        
        
}

- (void)setInputFileNameFromButton:(id)sender
{
	NSOpenPanel *openPanel;
        int result;
        NSArray *types = [NSArray arrayWithObject:@"pdf"];

        openPanel = [NSOpenPanel openPanel];
        [openPanel setAllowsMultipleSelection:NO];
        result = [openPanel runModalForTypes:types];
        if (result == NSOKButton) {
                [inputFileName setStringValue:[openPanel filename]];
        }
        
}

- (void)setOutputFileNameFromButton:(id)sender
{
	NSSavePanel *savePanel;
        int result;
        
        savePanel = [NSSavePanel savePanel];
        if ([convertToPS state]) {
                [savePanel setRequiredFileType:@"ps"];
    	} else {
                [savePanel setRequiredFileType:@"txt"];
        }

        result = [savePanel runModalForDirectory:NSHomeDirectory() file:@""];
        if (result == NSOKButton) {
                [outputFileName setStringValue:[savePanel filename]];
        }
        
}

@end
