#import "myResults.h"
#import "prefBoss.h"
#import "setMacroWatcher.h"
#import "utils.h"

@implementation setMacroWatcher
-(id) init
{
    currMacro = nil;
    return self;
}

-(IBAction) addAutoHistory: (id) sender
{
    NSMutableArray *pr;
    if(!currMacro) currMacro = [[NSMutableDictionary alloc] init];
    if((pr = [currMacro objectForKey: @"program"]) == nil)
    {
        pr = [[NSMutableArray alloc] init];
        [currMacro setObject: pr forKey: @"program"];
    }
    [pr addObjectsFromArray: [myOverLord autoHistory]];
    if([startMenu indexOfItemWithTitle: [myOverLord autoHistoryStart]] >= 0)
        [startMenu selectItemWithTitle: [myOverLord autoHistoryStart]];
    [macroView reloadData];
}
- (IBAction) addCodeSetStep: (id)sender
{
    BOOL ex;
    NSMutableDictionary *aa;
    NSMutableArray *pr;
    
    if(!currMacro) currMacro = [[NSMutableDictionary alloc] init];
    if((pr = [currMacro objectForKey: @"program"]) == nil)
    {
        pr = [[NSMutableArray alloc] init];
        [currMacro setObject: pr forKey: @"program"];
    }
    if([codeSetExact state] == NSOnState) 
        ex = YES;
    else
        ex = NO;
    aa = [[NSMutableDictionary alloc] init];
    [aa setObject: @"sel" forKey: @"stepType"];
    [aa setObject: [NSNumber numberWithInt: SELECTCODESET]
           forKey: @"mode"];
    [aa setObject: [NSNumber numberWithInt: [[codeSetSelMenu selectedItem] tag]] forKey: @"type"];
    [aa setObject: [[[codeSetMenu titleOfSelectedItem] copy] autorelease] forKey: @"name"];
    [aa setObject: [NSNumber numberWithBool: ex] forKey: @"exact"];
    [pr addObject: [aa autorelease]];
    [macroView reloadData];
    
}
- (IBAction)addSelectStep:(id)sender
{
    NSMutableDictionary *aa;
    NSMutableArray *pr;
    if(!currMacro) currMacro = [[NSMutableDictionary alloc] init];
    if((pr = [currMacro objectForKey: @"program"]) == nil)
    {
        pr = [[NSMutableArray alloc] init];
        [currMacro setObject: pr forKey: @"program"];
    }
    
    aa = [[NSMutableDictionary alloc] init];
    [aa setObject: @"sel" forKey: @"stepType"];
    [aa setObject: [NSNumber numberWithInt: [[selectModeMenu selectedItem] tag]]
        forKey: @"mode"];
    [aa setObject: [NSNumber numberWithInt: [[selectTypeMenu selectedItem] tag]] 
        forKey: @"type"];
    [aa setObject: [[[selectStringView stringValue] copy] autorelease]
        forKey: @"searchValue"];
    [aa setObject: [[[columnMenu titleOfSelectedItem] copy] autorelease] forKey: @"col"];
    [aa setObject: [NSNumber numberWithInt: [fpOption intValue]] forKey: @"float"];
    [aa setObject: [NSNumber numberWithInt: [regexOption intValue]] forKey: @"regex"];
    [pr addObject: [aa autorelease]];
    [macroView reloadData];
        
}
-(IBAction) addAutosetStep: (id) sender
{
    NSMutableDictionary *aa;
    NSMutableArray *pr;
    if([localAutosetMenu numberOfItems] == 0) 
    {
        NSWARNING(@"No defined sets.");
        return;
    }
    if(!currMacro) currMacro = [[NSMutableDictionary alloc] init];
    if((pr = [currMacro objectForKey: @"program"]) == nil)
    {
        pr = [[NSMutableArray alloc] init];
        [currMacro setObject: pr forKey: @"program"];
    }
    
    aa = [[NSMutableDictionary alloc] init];
    [aa setObject: @"autoset" forKey: @"stepType"];
    [aa setObject: [[[localAutosetMenu titleOfSelectedItem] copy] autorelease]
           forKey: @"name"];
    [pr addObject: [aa autorelease]];
    [macroView reloadData];
    
    
}

- (IBAction)addSetStep:(id)sender
{
    NSMutableDictionary *aa;
    NSMutableArray *pr;
    if([setObjectMenu numberOfItems] == 0) 
    {
        NSWARNING(@"No defined sets.");
        return;
    }
    if(!currMacro) currMacro = [[NSMutableDictionary alloc] init];
    if((pr = [currMacro objectForKey: @"program"]) == nil)
    {
        pr = [[NSMutableArray alloc] init];
        [currMacro setObject: pr forKey: @"program"];
    }
    
    aa = [[NSMutableDictionary alloc] init];
    [aa setObject: @"set" forKey: @"stepType"];
    [aa setObject: [NSNumber numberWithInt: [[setOpMenu selectedItem] tag]]
        forKey: @"op"];
    [aa setObject: [[[setObjectMenu titleOfSelectedItem] copy] autorelease]
        forKey: @"obj"];
    [pr addObject: [aa autorelease]];
    [macroView reloadData];

}
- (IBAction)cancelMacro:(id)sender
{
    [macroSheet orderOut: sender];
    [NSApp endSheet: macroSheet returnCode: 0];

}


- (IBAction)deleteAllSteps:(id)sender
{
    NSMutableArray *pr;
    if(!currMacro) currMacro = [[NSMutableDictionary alloc] init];
    if((pr = [currMacro objectForKey: @"program"]) == nil)
    {
        pr = [[NSMutableArray alloc] init];
        [currMacro setObject: pr forKey: @"program"];
    }
    else
        [pr removeAllObjects];
    [macroView reloadData];
}

- (IBAction)deleteStep:(id)sender
{
    int n;

    if((n = [macroView selectedRow]) >= 0 && [currMacro objectForKey: @"program"] != nil)
    {
        [[currMacro objectForKey: @"program"] removeObjectAtIndex: n];
    }
    [macroView reloadData];
}

- (IBAction)loadMacro:(id)sender
{
    NSMutableArray *revProg;
    int n;
    if([macroMenu numberOfItems] == 0) return;
    //need to do memory mgmt here
    //[self zeroEditor: self];
    [currMacro removeAllObjects];
    revProg = [NSMutableArray array];
    [currMacro addEntriesFromDictionary: [myOverLord autoSetForName: [macroMenu titleOfSelectedItem]]];
    //[[myOverLord autoSets] objectForKey: [macroMenu titleOfSelectedItem]]];
    [revProg setArray: [currMacro objectForKey: @"program"]];
    n = [revProg count];
    [currMacro setObject: revProg forKey: @"program"];
    [nameView setStringValue: [macroMenu titleOfSelectedItem]];
    [startMenu selectItemWithTitle: [currMacro objectForKey: @"start"]];
    [globalScope setIntValue: [[currMacro objectForKey: @"global"] intValue]];
    if([currMacro objectForKey: @"sort"] != nil)
        [sortSwitch setState: NSOnState];
    else
        [sortSwitch setState: NSOffState];
    [macroView reloadData];
}

- (IBAction)moveDown:(id)sender
{
    int n, m;
    NSMutableArray *where;
    n=0;
    if ((where = [currMacro objectForKey: @"program"]) != nil)
    {
        m = [where count];
        n = [macroView selectedRow];
        if(n < m - 1)
        {	
            [where exchangeObjectAtIndex: n
                withObjectAtIndex: n+1];

        }
    }
    [macroView reloadData];
    [macroView selectRow: n + 1 byExtendingSelection: NO];
}

- (IBAction)moveUp:(id)sender
{
    int n;
    NSMutableArray *where;
    if((n = [macroView selectedRow]) >= 0 && 
        (where = [currMacro objectForKey: @"program"]) != nil)
    {
        if(n > 0)
        {	
            [where exchangeObjectAtIndex: n
                withObjectAtIndex: n-1];
        }
    }
    [macroView reloadData];
    [macroView selectRow: n - 1  byExtendingSelection: NO];
}
- (IBAction) deleteMacro: (id) sender
{
    if([macroMenu numberOfItems] == 0) return;
    if(NSYESNOQUESTION(@"Delete auto set?") == NO) return;
    //need to do memory mgmt here
    [myOverLord removeAutoSetForName: [macroMenu titleOfSelectedItem]];
    [myOverLord rebuildAutoSetMenu];
    [self zeroEditor: nil];
}
- (IBAction)runMacro:(id)sender
{
    
    
    [macroSheet orderOut: sender];
    [NSApp endSheet: macroSheet returnCode: 1];

}

-(void) rebuildMenus
{
    int i, n, m;
    NSMutableDictionary *macros;
    NSArray *macroNames;
    
    macros = [myOverLord autoSets];
    macroNames = [myOverLord allAutoSetNames];
    //build menus
    
    //start menu
    n = [startMenu numberOfItems];
    if(n >= 2)
        for(i = 2; i < n; i++)
        {
            [startMenu removeItemAtIndex: 2];
        }
            
    m = [macroNames count];
    if(m > 0)
        for(i = 0; i < m; i++)
        {
            [startMenu addItemWithTitle: [macroNames objectAtIndex: i]];
        }
        //if(m>0)[startMenu selectItemAtIndex: 0];
    
    
    //macro names
    [macroMenu removeAllItems];
    if(m > 0)
        for(i = 0; i < m; i++)
        {
            [macroMenu addItemWithTitle: [macroNames objectAtIndex: i]];
        }
            if(m>0) [macroMenu selectItemAtIndex: 0];
    
    
    //set Objects
    [setObjectMenu removeAllItems];
    if(m > 0)
        for(i = 0; i < m; i++)
        {
            [setObjectMenu addItemWithTitle: [macroNames objectAtIndex: i]];
        }
            if(m>0) [setObjectMenu selectItemAtIndex: 0];
    //set autosets
    [localAutosetMenu removeAllItems];
    if(m > 0)
        for(i = 0; i < m; i++)
        {
            [localAutosetMenu addItemWithTitle: [macroNames objectAtIndex: i]];
        }
            if(m>0) [localAutosetMenu selectItemAtIndex: 0];
    //column names
    [columnMenu removeAllItems];
    m = [[myOverLord columns] count];
    if(m > 0)
        for(i = 0; i < m; i++)
        {
            [columnMenu addItemWithTitle: [[myOverLord columns] objectAtIndex: i]];
        }
            if(m>0) [columnMenu selectItemAtIndex: 0];
    
    
    [setOpMenu  selectItemAtIndex: 0];
    [selectTypeMenu  selectItemAtIndex: 0];
    [selectModeMenu  selectItemAtIndex: 0];    
}
-(IBAction) zeroEditor: (id) sender
{
    int i, n, m;
    NSMutableDictionary *macros;
    NSArray *macroNames;
    
    macros = [myOverLord autoSets];
    macroNames = [myOverLord allAutoSetNames];
    currMacro = [[NSMutableDictionary alloc] init];
    [nameView setStringValue: @""];
    [selectStringView setStringValue: @""];
    [fpOption setState: NSOffState];
    [regexOption setState: NSOffState];
    
    
    //build menus
    
    //start menu
    n = [startMenu numberOfItems];
    if(n >= 2)
        for(i = 2; i < n; i++)
        {
            [startMenu removeItemAtIndex: 2];
        }
    
    m = [macroNames count];
    if(m > 0)
        for(i = 0; i < m; i++)
        {
            [startMenu addItemWithTitle: [macroNames objectAtIndex: i]];
        }
    if(m>0)[startMenu selectItemAtIndex: 0];

    
    //macro names
    [macroMenu removeAllItems];
    if(m > 0)
        for(i = 0; i < m; i++)
        {
            [macroMenu addItemWithTitle: [macroNames objectAtIndex: i]];
        }
    if(m>0) [macroMenu selectItemAtIndex: 0];
    
    //code sets
    [codeSetSelMenu selectItemAtIndex: 0];
    [codeSetExact setState: NSOnState];
    [codeSetMenu removeAllItems];
    [codeSetMenu addItemsWithTitles: [[myOverLord getGWorkBench: nil] allCodeSetNames]];
    if([codeSetMenu numberOfItems] >= 1) [codeSetMenu selectItemAtIndex: 0];
    //set Objects
    [setObjectMenu removeAllItems];
    if(m > 0)
        for(i = 0; i < m; i++)
        {
            [setObjectMenu addItemWithTitle: [macroNames objectAtIndex: i]];
        }
    if(m>0) [setObjectMenu selectItemAtIndex: 0];
    //set autosets
    [localAutosetMenu removeAllItems];
    if(m > 0)
        for(i = 0; i < m; i++)
        {
            [localAutosetMenu addItemWithTitle: [macroNames objectAtIndex: i]];
        }
        if(m>0) [localAutosetMenu selectItemAtIndex: 0];
    //column names
    [columnMenu removeAllItems];
    m = [[myOverLord columns] count];
    if(m > 0)
        for(i = 0; i < m; i++)
        {
            [columnMenu addItemWithTitle: [[myOverLord columns] objectAtIndex: i]];
        }
    if(m>0) [columnMenu selectItemAtIndex: 0];
    

    [setOpMenu  selectItemAtIndex: 0];
    [selectTypeMenu  selectItemAtIndex: 0];
    [selectModeMenu  selectItemAtIndex: 0];
    [macroView reloadData];
    
    
}
-(void) saveMacro: (id) sender
{
    if([[nameView stringValue] isEqualToString: @""] == YES )
    {
        NSWARNING(@"You need to give the auto set a unique name");
        return;
    }
    if([myOverLord validAutoSetName: [nameView stringValue]] == NO)
    {
        if( NSYESNOQUESTION(@"Write on top of existing auto set with that name?") == YES)
        {
            [myOverLord removeAutoSetForName:  [nameView stringValue]];
        }
        else
            return;
    }
    [currMacro setObject: [[[startMenu titleOfSelectedItem] copy] autorelease]
                  forKey: @"start"];
    [currMacro setObject: [NSNumber numberWithInt: [globalScope intValue]] forKey: @"global"];
    if([sortSwitch state] == NSOnState)
        [currMacro setObject: [myOverLord sortStackCopy] forKey: @"sort"];
    [myOverLord addAutoSet: [[currMacro copy] autorelease] withName: [nameView stringValue]];
    [self rebuildMenus];
    [macroMenu selectItemWithTitle: [nameView stringValue]];
    if([startMenu indexOfItemWithTitle: [currMacro objectForKey: @"start"]] >= 0)
        [startMenu selectItemWithTitle: [currMacro objectForKey: @"start"]];
    [myOverLord rebuildAutoSetMenu];
    

}
-(void) macroEditorDidEnd: (NSWindow *) mySheet returnCode: (int) returnCode contextInfo: (void *) contextInfo
{
    if(returnCode == 0) return;
    //put in runningstuff
    [myOverLord doAutoSet: [macroMenu selectedItem]];
    [myOverLord rebuildAutoSetMenu];


}
-(void) runMacroEditor
{
    NSWindow *who;
    
    [self zeroEditor: self];
    if([gPrefBoss detachedSheetValue])
        who = nil;
    else
        who = [myOverLord myWindow];
    
     [NSApp beginSheet: macroSheet
        modalForWindow: who
	modalDelegate: self
	didEndSelector: @selector(macroEditorDidEnd:returnCode:contextInfo:)
	contextInfo: nil];

}

- (int)numberOfRowsInTableView:(NSTableView *)aTableView
{
    if(currMacro)
        return [[currMacro objectForKey: @"program"] count];
    else
        return 0;
}

- (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(int)rowIndex
{
    NSArray *arr;
    NSMutableDictionary *md;
    if(currMacro)
    {
        arr = [currMacro objectForKey: @"program"];
        md = [arr objectAtIndex: rowIndex];
        if([[md objectForKey: @"stepType"] isEqualToString: @"sel"] == YES)
        {
            NSMutableString *flagStr = [NSMutableString string];
            int ff;
            ff = 0;
            if([[md objectForKey: @"mode"] intValue] == SELECTCODESET)
            {
                NSString *csItem;
                if([md objectForKey: @"type"] == nil)
                    [md setObject: [NSNumber numberWithInt: SELECT] forKey: @"type"];
                if([md objectForKey: @"exact"] == nil)
                    [md setObject: [NSNumber numberWithBool: YES] forKey: @"exact"];
                switch([[md objectForKey: @"type"] intValue])
                {
                    case SELECT:
                        csItem = [NSString stringWithFormat: @"%d %@: %@", rowIndex+1, @"Code set", 
                            [md objectForKey: @"name"]];
                        break;
                    case SELECTFEWER:
                        csItem = [NSString stringWithFormat: @"%d %@: %@", rowIndex+1, @"-Code set", 
                            [md objectForKey: @"name"]];
                        break;
                    case SELECTADDITIONAL:
                        csItem = [NSString stringWithFormat: @"%d %@: %@", rowIndex+1, @"+Code set", 
                            [md objectForKey: @"name"]];
                        break;
                }
                if([[md objectForKey: @"exact"] boolValue] == YES)
                    return [NSString stringWithFormat: @"%@ (x)", csItem];
                return csItem;
            }
            if([[md objectForKey: @"mode"] intValue] == SELECTREVERSE)
            {
                return [NSString stringWithFormat: @"%d %@", rowIndex+1, @"Select reverse"];
            }
            [flagStr setString: @"("];
            if([[md objectForKey: @"float"] intValue] == 1)
            {
                ff++;
                [flagStr appendString: @"float"];
            }
            if([[md objectForKey: @"regex"] intValue] == 1)
            {
                if(ff) [flagStr appendString: @", "];
                [flagStr appendString: @"regex"];
                ff++;
            }
            if(ff)
                [flagStr appendString: @")"];
            else
                [flagStr setString: @""];
            
            return [NSString stringWithFormat: @"%d %@: \"%@\" in %@ %@", rowIndex + 1,
                [[selectModeMenu itemAtIndex: [selectModeMenu indexOfItemWithTag: [[md objectForKey: @"mode"] intValue]]]  title],
                [md objectForKey: @"searchValue"],
                [md objectForKey: @"col"],
                flagStr];
        }
        else if ([[md objectForKey: @"stepType"] isEqualToString: @"set"] == YES)
        {
            return [NSString stringWithFormat: @"%d %@: \"%@\" with %@", rowIndex + 1,
                [md objectForKey: @"stepType"],
                [[setOpMenu itemAtIndex: [setOpMenu indexOfItemWithTag: [[md objectForKey: @"op"] intValue]]] title],
                [md objectForKey: @"obj"]
                ];
        }
        else if([[md objectForKey: @"stepType"] isEqualToString: @"autoset"] == YES)
        {
            return [NSString stringWithFormat: @"%d %@: %@", rowIndex + 1,
                [md objectForKey: @"stepType"],
                [md objectForKey: @"name"]
                ];
            
        }
    }
    return @"";

}
@end
