#import "appDelegate.h"
#import "myProject.h"
#import "utils.h"
#import "TAMSCharEngine.h"
NSString * TAWorkItems = @"The items that appear in the work menu";
#define WORKBASE 4

int pathNameComp(id first, id second, NSString *key)
{
    return [[first lastPathComponent] compare: [second lastPathComponent] options: NSCaseInsensitiveSearch];
}



@implementation appDelegate

//- (void)applicationDidFinishLaunching:(NSNotification *)aNotification

- (id) init
{
    [super init];

    return self;
}

- (NSMenuItem *) reanalysisMenu
{
    return reanalysisMenu;
}
- (NSMenuItem *) docMacroMenu
{
    return docMacroMenu;
}
- (NSMenuItem *) toggleShowTagsMenuItem
{
    return toggleShowTagsMenuItem;
}

- (NSMenuItem *) codeSetMenu
{
    return codeSetMenu;
}
- (NSMenuItem *) summReportMenu
{
    return summReportMenu;
}

- (NSMenuItem *) rebuildMenuItem
{
    return rebuildMenuItem;
}
- (NSMenuItem *) autoSetMenu
{
    return autoSetMenu;
}
- (NSMenuItem *) fileSetMenu
{
    return fileSetMenu;
}
-(NSMenuItem *) rsltCodeSetMenu { return rsltCodeSetMenu;}

-(NSMenuItem *) caseMenuItem {return caseMenuItem;}

- (NSMenuItem *) namedSelectionMenu {return namedSelectionMenu;}

- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender
{
   //Must replace this with unsaved files.... [gWorkBench back];
   // return NSTerminateLater;
	if(NSYESNOQUESTION(@"Have you saved all your documents? Should I quit?\n(Yes means unsaved changes will be lost)"))
	   return NSTerminateNow;
       else return NSTerminateLater;
}


#define NSDEF [NSUserDefaults standardUserDefaults]

- (void)applicationWillFinishLaunching:(NSNotification *)aNotification

{
//handle user defaults    
    
    if(!pb)
	pb = [[prefBoss alloc] init];
    if([NSDEF objectForKey: TADateStampKey] == nil)
	    [[NSUserDefaults standardUserDefaults] setInteger: 0
	    forKey: TADateStampKey];
    if([NSDEF objectForKey: TAPromptKey] == nil)
	[[NSUserDefaults standardUserDefaults] setInteger: 1
	forKey: TAPromptKey];
    if([NSDEF objectForKey: TAMacNLKey] == nil)
	[[NSUserDefaults standardUserDefaults] setInteger: 0
	forKey: TAMacNLKey];
    if([NSDEF objectForKey: TAAutoReloadKey] == nil)
	[[NSUserDefaults standardUserDefaults] setInteger: 1
	forKey: TAAutoReloadKey];
    if([NSDEF objectForKey: TACodeFromList] == nil)
	[[NSUserDefaults standardUserDefaults] setInteger: 1
	forKey: TACodeFromList ];
    if([NSDEF objectForKey: TACheckCodeDefinition] == nil)
	[[NSUserDefaults standardUserDefaults] setInteger: 0
                                forKey: TACheckCodeDefinition ];
    
    if([NSDEF objectForKey: TAUseToolTip] == nil)
	[[NSUserDefaults standardUserDefaults] setInteger: 0
	forKey: TAUseToolTip ];
    if([NSDEF objectForKey: TACountSections] == nil)
	[[NSUserDefaults standardUserDefaults] setInteger: 1
	forKey: TACountSections ];
    if([NSDEF objectForKey: TAHCLStackSize] == nil)
	[[NSUserDefaults standardUserDefaults] setInteger: 6
                                                   forKey: TAHCLStackSize ];
    if([NSDEF objectForKey: TAUseCoder] == nil)
	[[NSUserDefaults standardUserDefaults] setInteger: 0
	forKey: TAUseCoder ];
    if([NSDEF objectForKey: TAAutoBackspace] == nil)
	[[NSUserDefaults standardUserDefaults] setInteger: 0
                                                   forKey: TAAutoBackspace ];
    if([NSDEF objectForKey: TACoderID] == nil)
	[[NSUserDefaults standardUserDefaults] setObject: @""
	forKey: TACoderID ];

   if([NSDEF objectForKey: TAGGVDir] == nil)
	[[NSUserDefaults standardUserDefaults] setObject: @"/usr/X11R6/bin/gv"
            forKey: TAGGVDir ];
   if([NSDEF objectForKey: TAGDotDir] == nil)
	[[NSUserDefaults standardUserDefaults] setObject: @"/usr/bin/dot"
            forKey: TAGDotDir ];
   if([NSDEF objectForKey: TAGUseGV] == nil)
	[[NSUserDefaults standardUserDefaults] setInteger: 1
                                                   forKey: TAGUseGV ];





    if([NSDEF objectForKey: TAAVCode] == nil)
	[[NSUserDefaults standardUserDefaults] setObject: @"_time"
            forKey: TAAVCode ];
    if([NSDEF objectForKey: TAShowCoder] == nil)
	[[NSUserDefaults standardUserDefaults] setInteger: 1
	forKey: TAShowCoder ];
    if([NSDEF objectForKey: TAEOFIsEnd] == nil)
	[[NSUserDefaults standardUserDefaults] setInteger: 1
	forKey: TAEOFIsEnd];
    if([NSDEF objectForKey: TACommentForCode] == nil)
	[[NSUserDefaults standardUserDefaults] setInteger: 1
	forKey: TACommentForCode];
    if([NSDEF objectForKey: TAZapUnivAtEOF] == nil)
	[[NSUserDefaults standardUserDefaults] setInteger: 1
	forKey: TAZapUnivAtEOF];
    if([NSDEF objectForKey: TASaveGraphviz] == nil) 
	[[NSUserDefaults standardUserDefaults] setInteger: 0
        forKey: TASaveGraphviz];
    if([NSDEF objectForKey: TAMetaColor] == nil && [NSDEF objectForKey: TADefaultUnstruct] == nil) //this is basically checking for a previous install
    {
            [[NSUserDefaults standardUserDefaults] setInteger: 1
                        forKey: TADefaultUnstruct];
    }
    else
    {
        if([NSDEF objectForKey: TADefaultUnstruct] == nil) 
            [[NSUserDefaults standardUserDefaults] setInteger: 0
                                    forKey: TADefaultUnstruct];
        
    }
    if([NSDEF objectForKey: TAScanInit] == nil)
	[[NSUserDefaults standardUserDefaults] setInteger: 1
	forKey: TAScanInit];
    if([NSDEF objectForKey: TATimeFormatHHMMSS] == nil)
	[[NSUserDefaults standardUserDefaults] setInteger: 0
	forKey: TATimeFormatHHMMSS];
    if([NSDEF objectForKey: TACodeAV] == nil)
	[[NSUserDefaults standardUserDefaults] setInteger: 1
            forKey: TACodeAV];
    if([NSDEF objectForKey: TAAVBackspace] == nil)
	[[NSUserDefaults standardUserDefaults] setInteger: 3
                forKey: TAAVBackspace];
    if([NSDEF objectForKey: TAMetaColor] == nil)
    {
        NSData *dd;
        
        
            dd = [NSArchiver archivedDataWithRootObject: [NSColor blackColor]];
            [[NSUserDefaults standardUserDefaults] setObject: dd
                                                      forKey: TAMetaColor];
        
    }
    if([NSDEF objectForKey: TARealColor] == nil)
    {
        NSData *dd;
        
         if([NSDEF objectForKey: TATagColor] == nil)
         {
             dd = [NSArchiver archivedDataWithRootObject: [NSColor blackColor]];
             [[NSUserDefaults standardUserDefaults] setObject: dd
                                                        forKey: TARealColor];
        }
        else
        {
            dd = [NSArchiver archivedDataWithRootObject: getColorForInt([gPrefBoss tagColorValue])];
            [[NSUserDefaults standardUserDefaults] setObject: dd
                                                      forKey: TARealColor];            
        }
    }
    if([NSDEF objectForKey: TAAutoColor] == nil)
	[[NSUserDefaults standardUserDefaults] setInteger: 1
	forKey: TAAutoColor];
    if([NSDEF objectForKey: TAEscapeBraces] == nil)
	[[NSUserDefaults standardUserDefaults] setInteger: 1
	forKey: TAEscapeBraces];
    if([NSDEF objectForKey: TANonSimpleRepeat] == nil)
	[[NSUserDefaults standardUserDefaults] setInteger: 0
        forKey: TANonSimpleRepeat];
    if([NSDEF objectForKey: TABatchOpenFiles] == nil)
	[[NSUserDefaults standardUserDefaults] setInteger: 0
                                                   forKey: TABatchOpenFiles];
    if([NSDEF objectForKey: TAEnableBack] == nil)
	[[NSUserDefaults standardUserDefaults] setInteger: 1
            forKey: TAEnableBack];
    if([NSDEF objectForKey: TAGuessUpdate] == nil)
	[[NSUserDefaults standardUserDefaults] setInteger: 0
	forKey: TAGuessUpdate];
    if([NSDEF objectForKey: TADetachedSheet] == nil)
	[[NSUserDefaults standardUserDefaults] setInteger: 0
	forKey: TADetachedSheet];
    if([NSDEF objectForKey: TAZoomFactor] == nil)
	[[NSUserDefaults standardUserDefaults] setInteger: 25
	forKey: TAZoomFactor];

    if([NSDEF objectForKey: TAUnichar] == nil)
	[[NSUserDefaults standardUserDefaults] setInteger: 608
	forKey: TAUnichar];

    if([NSDEF objectForKey: TATagColor] == nil)
	[[NSUserDefaults standardUserDefaults] setInteger: 0
	forKey: TATagColor];
    if([NSDEF objectForKey: TAScanForLN] == nil)
	[[NSUserDefaults standardUserDefaults] setInteger: 1
	forKey: TAScanForLN];
    if([NSDEF objectForKey: TACancelAfterAddCode] == nil)
	[[NSUserDefaults standardUserDefaults] setInteger: 1
	forKey: TACancelAfterAddCode];
    if([NSDEF objectForKey: TACancelAfterRecode] == nil)
	[[NSUserDefaults standardUserDefaults] setInteger: 1
                                                   forKey: TACancelAfterRecode];
    if([NSDEF objectForKey: TAWorkItems] == nil)
    {
        NSData *dd;
        
        
        dd = [NSArchiver archivedDataWithRootObject: [NSMutableArray array]];
        [[NSUserDefaults standardUserDefaults] setObject: dd
                                                  forKey: TAWorkItems];
        
    }
    [[NSWorkspace sharedWorkspace] findApplications];
    
    //initSearchListSystem();
    //if([NSDEF objectForKey:TASavedState] == nil) [wb zapStates: self];


}

- (void) doCodeDictionary: (NSMutableDictionary *) cl from: (myProject *) who
{
    NSModalSession td;
    
    if(!cd)
	cd = [[codeBrowser alloc] init];
    [cd setDict: cl from: who];
    td = [NSApp beginModalSessionForWindow:[cd window]];
    while([NSApp runModalSession: td] == NSRunContinuesResponse)
        ;
    [NSApp endModalSession: td];

    //[cd showWindow: self];
}
-(NSMutableArray *) getWorkItems
{
    NSMutableArray *swi=[NSMutableArray array];;
    NSData *dd =  [[NSUserDefaults standardUserDefaults] objectForKey:
	TAWorkItems];
    NSArray *wh = [NSUnarchiver unarchiveObjectWithData:dd];
    FORALL(wh)
    {
        if([[NSFileManager defaultManager] fileExistsAtPath: temp] == YES)
            [swi addObject: temp];
    }
    ENDFORALL;
        
    //swi = [NSMutableArray arrayWithArray: wh];
    [swi sortUsingFunction: pathNameComp context: nil];
    return swi;
    

}
-(void) setWorkItems: (NSArray *) xwi
{
    NSMutableArray *wi;
    NSData *dd;
    wi = [NSMutableArray arrayWithArray: xwi];
    [wi sortUsingFunction: pathNameComp context: nil];
    dd= [NSArchiver archivedDataWithRootObject: wi];
    [[NSUserDefaults standardUserDefaults] setObject: dd
                                              forKey: TAWorkItems];
    
    
}


-(void) rebuildWorkMenu: (NSMenu *) myMen atBase: (int) nn withAction: (BOOL) act withExistCheck: (BOOL) exist
{
    int n,i;
    NSMutableArray *wiArray;
    n = [myMen numberOfItems];
    for(i = n-1; i >= nn; i--)
    {
	[myMen removeItemAtIndex: i];
    }
    wiArray = [NSMutableArray arrayWithArray: [self getWorkItems]];
    [wiArray sortUsingFunction: pathNameComp context: nil];
    FORALL(wiArray)
    {
        NSMenuItem *mm;
        if(exist) if([[NSFileManager defaultManager] fileExistsAtPath: temp] == NO) continue;
        mm = [[NSMenuItem alloc] init];
        [mm setTitle: [temp lastPathComponent]];
        if(act)
        {
            [mm setTarget: self];
            [mm setAction: @selector(loadWorkItem:)];
        }
        [mm setTag: __i];
                
         [myMen addItem: mm];
    }
    ENDFORALL;
    
    
}
-(IBAction) clearAllWorkItems: (id) sender
{
    if(NSYESNOQUESTION(@"Remove all work items?") == NO) return;
    [self setWorkItems: [NSMutableArray array]];
    [self rebuildWorkMenu: [workMenu submenu] atBase: WORKBASE withAction: YES withExistCheck: YES];
    
}
-(void) delWorkDidEnd: (NSWindow *) mySheet returnCode: (int) returnCode contextInfo: (void *) contextInfo
{
    NSMutableArray *wi = [self getWorkItems];
    int m;
    switch(returnCode)
    {
        case 1:
            //delete the selected item;
            m = [[delWorkMenu selectedItem] tag];
            [wi removeObjectAtIndex: m];
            [self setWorkItems: wi];
            [self rebuildWorkMenu: [workMenu submenu] atBase: WORKBASE withAction: YES withExistCheck: YES];
            break;

        case 2:
            //delete all items;
            [self setWorkItems: [NSMutableArray array]];
            [self rebuildWorkMenu: [workMenu submenu] atBase: WORKBASE withAction: YES withExistCheck: YES];
            break;
        default: ;
                   
            
    }
    
}

-(IBAction) loadWorkItem: (id) sender
{
    [[NSDocumentController sharedDocumentController]
        openDocumentWithContentsOfFile: [[self getWorkItems] objectAtIndex: [sender tag]]
                               display: YES];
}
-(IBAction) cancelRemoveWorkItem: (id) sender
{
    [delWorkPanel orderOut: sender];
    [NSApp endSheet: delWorkPanel returnCode: 0];
    
}

-(IBAction) okRemoveWorkItem: (id) sender
{
    [delWorkPanel orderOut: sender];
    [NSApp endSheet: delWorkPanel returnCode: 1];
    
}

-(IBAction) deleteAllWorkItems: (id) sender
{
    if(NSYESNOQUESTION(@"Remove all work items?") == NO) return;
    [delWorkPanel orderOut: sender];
    [NSApp endSheet: delWorkPanel returnCode: 2];
    
}
-(IBAction) removeWorkItem: (id) sender
{
    if([[self getWorkItems] count] == 0) return;
    [self rebuildWorkMenu: [delWorkMenu menu] atBase: 0 withAction: NO withExistCheck: NO];
    [NSApp beginSheet: delWorkPanel
       modalForWindow: nil
	modalDelegate: self
       didEndSelector: @selector(delWorkDidEnd:returnCode:contextInfo:)
          contextInfo: nil];}
-(IBAction) addWorkItem: (NSString *) path
{
    NSMutableArray *wi;
    wi = [self getWorkItems];
    if(addUniqueToArray(wi, path) == YES)
    {
        [self setWorkItems: wi];
        [self rebuildWorkMenu: [workMenu submenu] atBase: WORKBASE withAction: YES withExistCheck: YES];
    }
}
- (void) doPreference: (id) sender
{
    if(!pb)
	pb = [[prefBoss alloc] init];
    [pb showWindow: self];
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    [self rebuildWorkMenu: [workMenu submenu] atBase: WORKBASE withAction: YES withExistCheck: YES];
    
}
-(IBAction) aboutApp: (id) sender
{
	NSMESSAGE(@"GTAMSAnalyzer version .42\n(c) 2004 by Matthew Weinstein\nIncludes:\nAGRegex (c) Aram Greenman\nPCRE (c) Philip Hazel\nGorm fixes by Rob Burns");
}
@end
