#import "Controller.h"

@implementation Controller


- (void) focusToTex
{
    [theWindow makeFirstResponder:texView];
}


- (void) awakeFromNib
{
    NSBundle *mainBundle = [NSBundle mainBundle];

    bundlePath = [mainBundle bundlePath];
    [texView setRichText:NO];

    // Focus in the texview

    [self focusToTex];
    [theWindow makeKeyAndOrderFront:theWindow];

    [theDragView setImage:[NSImage imageNamed:@"tex2eps.eps"]];


    // all this voodoo around NSString's method stringByAppendingPathComponent is just
    // to let OpenStep handle around "/" and "\" as the path separator
    // below was system("mkdirs ~/Library/Tex2Eps"); & system("mkdirs ~/Library/Tex2Eps/tmp");
    // in mach 

    userlib = [[NSString alloc] initWithString:[[NSHomeDirectory()
                   stringByAppendingPathComponent:@"Library"]
                   stringByAppendingPathComponent:@"Tex2Eps"]];

    [[NSFileManager defaultManager] createDirectoryAtPath:userlib attributes:nil];

    usertmp = [[NSString alloc] initWithString:[userlib stringByAppendingPathComponent:@"tmp"]];
    [[NSFileManager defaultManager] createDirectoryAtPath:usertmp attributes:nil];

}


- (BOOL)applicationShouldTerminate:(NSApplication *)app 
{
    // was system("rm -f ~/Library/Tex2Eps/tmp");

    [[NSFileManager defaultManager] removeFileAtPath:usertmp handler:nil];
    return YES;
}



// Buttons in the MainWindow


- (void)latexCompile:(id)sender
{

    // is there a latex input ???, write to file,  run formel2eps.bat

    if ([[texView string] length] == 0)
      {
        NSRunAlertPanel(@"Tex2Eps", @"Fill some latex code in the field above !", @"OK", nil, nil);
        return;
      }

    [[texView string] writeToFile:[usertmp stringByAppendingPathComponent:@"tex2eps.tex"]
                       atomically:YES];


    // this is the only system call probably not working with other OpenStep platforms than mach

    system([[[bundlePath stringByAppendingPathComponent:@"Resources"]
                  stringByAppendingPathComponent:@"formel2eps.bat"] cString]);


    // NSImage +imageNamed  is not not working with fullpath names.
    // I hope, do not know, that NSImageView is releaseing the old NSImage, if there is one ???

    [theDragView setImage:[[NSImage alloc] initByReferencingFile:
        [usertmp stringByAppendingPathComponent:@"tex2eps.eps"]]];

    // Focus again in the texview

    [self focusToTex];
}


- (NSString*)tellMeTheEpsFile
{
    return [usertmp stringByAppendingPathComponent:@"tex2eps.eps"]; 
}


- (void)save:sender
{
    NSSavePanel *sp;

    sp = [NSSavePanel savePanel];
    [sp setRequiredFileType:@"tex"];

    if ([sp runModalForDirectory:userlib file:@""] == NSOKButton) 
        [[texView string] writeToFile:[sp filename] atomically:YES];

    [theWindow setTitleWithRepresentedFilename:[sp filename]];
    [self focusToTex];
}


- (void)load:sender
{
    NSOpenPanel *oPanel = [NSOpenPanel openPanel];

    // the Capacity is a hint, not a limit !
    NSMutableString *tempString = [NSMutableString stringWithCapacity:100];

    [oPanel setAllowsMultipleSelection:NO];

    if ( [oPanel runModalForDirectory:userlib
                                 file:nil
                                types:[NSArray arrayWithObject:@"tex"]] == NSOKButton)
      {
        [tempString initWithContentsOfFile:[[oPanel filenames] objectAtIndex:0] ];
        [texView setString:tempString];

        [theWindow setTitleWithRepresentedFilename:[[oPanel filenames] objectAtIndex:0]];
      }

    [self focusToTex];
}




- (void)showInfoPanel:sender
{
    if (!infoPanel) [NSBundle loadNibNamed:@"info.nib" owner:self];
    [infoPanel makeKeyAndOrderFront:self];
}


- (void)showFormatWindow:sender
{
    NSMutableString *tempString = [NSMutableString stringWithCapacity:100];

    if (!formatWindow)
      {
        [NSBundle loadNibNamed:@"format.nib" owner:self];
        [formatScript setRichText:NO];

        if ([[NSFileManager defaultManager] fileExistsAtPath:
            [userlib stringByAppendingPathComponent:@"tex2eps.bat"]])
            [tempString initWithContentsOfFile:[userlib stringByAppendingPathComponent:@"tex2eps.bat"]];
        else
            [tempString initWithContentsOfFile:
                [[bundlePath stringByAppendingPathComponent:@"Resources"]
                  stringByAppendingPathComponent:@"tex2eps.bat"]];
        
        [formatScript setString:tempString];
      }

    [formatWindow makeKeyAndOrderFront:self];
}



// Converter Script Customization

- (void)saveFormatWindow:sender
{
    [[formatScript string] writeToFile:[userlib stringByAppendingPathComponent:@"tex2eps.bat"] atomically:YES];

    // the chmod +x is obsolete in OpenStep NT
    system("chmod +x ~/Library/Tex2Eps/tex2eps.bat");

    [self focusToTex];
}


- (void)RevertFormatWindow:sender
{
    NSMutableString *tempString = [NSMutableString stringWithCapacity:100];

    [tempString initWithContentsOfFile: [[bundlePath stringByAppendingPathComponent:@"Resources"]
                  stringByAppendingPathComponent:@"tex2eps.bat"]];

    [formatScript setString:tempString];

    [self focusToTex];
}



@end
