#import "codeBrowser.h"
#import "tamsutils.h"
#import "prefBoss.h"

#define SELECTALL(X) [X setSelectedRange: NSMakeRange(0, [[X string] length])]
int codeCompare(id first, id second, void* context)
{
    return [(NSString *)first compare: second];
}


@implementation codeBrowser
-(IBAction) doInsertDate: (id) sender
{
    [codeDef insertText: [[NSDate date] description]];
}

-(void) loadData
{
    if(![self doSaveDefinition])
    {
        //[codeDef deselectRow: [codeDef selectedRow]];
        return;
    }
    [self blank];
    return;
}
-(id) init 
{
    self = [super initWithWindowNibName: @"codeBrowser"];
    backCL = [[NSMutableDictionary alloc] init];
    cl = nil;
    return self;
}
-(void) setDict: (NSMutableDictionary *) aCL from: (myProject *) who
{

    codeSource = who;
    if(cl)
    {
        [self doSaveDef: nil];
    }
    cl = aCL;
    [backCL setDictionary: aCL ];
    [codeName setStringValue: @""];
    SELECTALL(codeDef);
    [codeDef insertText: @""];
    //[codeDef setString: @""];
    [codeActive setState: NSOnState];
    //[codeList reloadData];
    [self blank];
}

-(void) windowDidLoad 
{
    [codeList setTarget: self];
    [codeList setAction: @selector(loadData)];
    [self blank];
}

- (int)numberOfRowsInTableView:(NSTableView *)aTableView
{
    NSMutableArray *mykeys;
    
    mykeys = [NSMutableArray arrayWithArray: [cl allKeys]];
    return [mykeys count];
}

-(NSString *) codeN: (int) n
{
   NSMutableArray *mykeys;
    
    if([[cl allKeys] count] == 0) return nil;
    mykeys = [NSMutableArray arrayWithArray: [cl allKeys]];
    [mykeys sortUsingFunction: codeCompare context: nil];
    return [mykeys objectAtIndex: n];
}
- (void)tableViewSelectionDidChange:(NSNotification *)aNotification
{
    [self doSaveDefinition];
    [self blank];
}
- (void)tableView:(NSTableView*)tableView didClickTableColumn:(NSTableColumn *)tableColumn
{
    [self tableViewSelectionDidChange: nil];
}
/*
- (void)tableViewSelectionDidChange:(NSNotification *)aNotification
{

    
}
*/
- (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(int)rowIndex
{
    NSMutableArray *mykeys;
    
    mykeys = [NSMutableArray arrayWithArray: [cl allKeys]];
    [mykeys sortUsingFunction: codeCompare context: nil];
    return [mykeys objectAtIndex: rowIndex];
}

/* the buttons */
-(void) blank
{
    int n;
    NSDictionary *who;
    NSString *myDef;
    NSString *tc;
    NSNumber *nn;
    [codeName setStringValue: @""];
    SELECTALL(codeDef);
    [codeDef insertText: @""];
    [codeColorWell setColor: [gPrefBoss realColor]];
    [inheritedColorSwitch setState: NSOnState];
    [codeActive setState: NSOnState];
    [codeList reloadData];
    n = [codeList selectedRow];
    if(n >=0)
    {
        NSColor *mycolor;
        tc = [self codeN: n];
        if(!tc) return;
        who = [cl objectForKey: tc];
        if (who)
        {
            [codeName setStringValue: tc];
            if([[who objectForKey: @"active"] isEqualToString: @"YES"] == YES)
                [codeActive setState: NSOnState];
            else
                [codeActive setState: NSOffState];            
            myDef = [who objectForKey: @"definition"];
            nn = [who objectForKey: @"color"];
            mycolor = [codeSource colorForCode: tc];
            [codeColorWell setColor: mycolor];
            if(nn == nil)
            {
                [inheritedColorSwitch setState: NSOnState];
                //[codeColorMenu selectItemAtIndex: [codeColorMenu indexOfItemWithTag: inheritedColor]];
            }
            else
            {
                int n;
                n = [nn intValue];
                switch(n)
                {
                    case inheritedColor:
                        [inheritedColorSwitch setState: NSOnState];
                        break;
                    case otherColor:
                        [inheritedColorSwitch setState: NSOffState];
                        if([who objectForKey: @"realColor"] != nil)
                            [codeColorWell setColor: [who objectForKey: @"realColor"]];
                        break;
                    default:
                        [inheritedColorSwitch setState: NSOffState];
                        [codeColorWell setColor: getColorForInt(n)];
                        break;
                };
            }
                        //look up color
                //[codeColorMenu selectItemAtIndex: [codeColorMenu indexOfItemWithTag: [nn intValue]]];
              [codeDef setString: myDef];
            [codeDef display];
        }
    }
    else     if([gPrefBoss dateTimeValue]) [self doInsertDate: self];
       
}

-(IBAction) doClearDef: (id) sender
{
    if(![self doSaveDefinition]) return;
    [codeName setStringValue: @""];
    [codeDef setString: @""];
    [codeColorWell setColor: [gPrefBoss realColor]];
    if([gPrefBoss dateTimeValue]) [self doInsertDate: self];
    [codeActive setState: NSOnState];
    [inheritedColorSwitch setState: NSOnState];
    //[codeColorMenu selectItemAtIndex: [codeColorMenu indexOfItemWithTag: inheritedColor]];
    [codeList deselectRow: [codeList selectedRow]];
    [codeList reloadData];
    [codeList deselectRow: [codeList selectedRow]];
}

-(IBAction) doSaveDef: (id) sender
{
        [self doSaveDefinition];
}

-(int) doSaveDefinition
{
    NSMutableDictionary *myEntry;
    int new;
    
    if([[codeName stringValue] isEqualToString: @""] == YES)
        return 1;
/*
    rr = [[[codeName stringValue] stringByTrimmingCharactersInSet: 
        [NSCharacterSet whitespaceAndNewlineCharacterSet] ] rangeOfCharacterFromSet:
        [NSCharacterSet  whitespaceCharacterSet]];
    if(rr.location != NSNotFound) 
    {
        NSWARNING(@"Illegal space character found in code name.");
        return 0;
    }
*/
    if(!isCodeNameLegal([[codeName stringValue] stringByTrimmingCharactersInSet: 
        [NSCharacterSet whitespaceAndNewlineCharacterSet]]))
    {
        NSWARNING(@"Illegal character found in code name.");
        return 0;
    
    }
    myEntry = [cl objectForKey: [codeName stringValue]];
    if(myEntry)
    {
        new = 0;
    }
    else
    {
        myEntry = [NSMutableDictionary dictionary];
        new = 1;
    }
    [myEntry setObject: [[[codeDef string] copy] autorelease] forKey: @"definition"];
    if([codeActive state] == NSOnState)
        [myEntry setObject: @"YES" forKey: @"active"];
    else
        [myEntry setObject: @"NO" forKey: @"active"];
    if([inheritedColorSwitch state] == NSOnState)
        [myEntry setObject: [NSNumber numberWithInt: inheritedColor] forKey: @"color"];
    else
    {
        [myEntry setObject: [NSNumber numberWithInt: otherColor] forKey: @"color"];
        [myEntry setObject: [[[codeColorWell color] copy] autorelease] forKey: @"realColor"];
            
    }
    //[myEntry setObject: [NSNumber numberWithInt: [[codeColorMenu selectedItem] tag]] forKey: @"color"];
    //if ( [[codeColorMenu selectedItem] tag] == otherColor) 
    //    [myEntry setObject: [[[codeColorWell color] copy] autorelease] forKey: @"realColor"];
    if(new)
        [cl setObject: myEntry forKey: [codeName stringValue]];
    [codeList reloadData];
    return 2;
    
}
-(IBAction) selectColorFromWell:(id)Sender
{
    [inheritedColorSwitch setState: NSOffState];
}
-(IBAction) selectColorFromSwitch:(id) sender
{
    if([inheritedColorSwitch state] == NSOnState) 
        [codeColorWell setColor: [codeSource colorForCode: [codeName stringValue]]];
}

-(BOOL) windowShouldClose: (NSNotification *)aNotification
{
    if([self doSaveDefinition]) return YES;
    else return NO;
}
- (void)windowWillClose:(NSNotification *)aNotification
{
    //[self doSaveDef: nil];
    cl = nil;
    [codeSource setCodeListDirty];
    [codeSource broadcastCodeChange: YES];

}


-(IBAction) doCloseDef: (id) sender
{
    if(![self doSaveDefinition]) return;
    [NSApp stopModal];
    [self close];
}
-(IBAction) doDeleteDef: (id) sender
{
    int n;
    
    n = [codeList selectedRow];
    if(n>=0)
    {
        [cl removeObjectForKey: [self codeN: n]];
        [self blank];
    }
}

-(IBAction) doRestoreDef: (id) sender
{
    [cl removeAllObjects];
    [cl setDictionary: backCL];
    [self blank];
}

-(IBAction) removeAllColors: (id) sender
{
    NSArray *codes;
    
        if(NSYESNOQUESTION(@"Should I proceed to make every color \"inherited color\"?") == YES)
        {
            //get the list
            codes = [cl allKeys];
            FORALL(codes)
            {
            //for each
                NSMutableDictionary *entry;
                entry = [NSMutableDictionary dictionaryWithDictionary: [cl objectForKey: temp]];
                [entry setObject: [NSNumber numberWithInt: inheritedColor] forKey: @"color"];
                [entry removeObjectForKey: @"realColor"];
                [cl setObject: entry forKey: temp];
            }
            ENDFORALL;
            //set color to inheritedColor
            [inheritedColorSwitch setState: NSOnState];
            [codeColorWell setColor: [gPrefBoss realColor]];
            //remove entry for realColor
            //flip switch
            //set color
        }
}
@end
