/*
        Copyright (c) 1996, NeXT Software, Inc.
        All rights reserved.

        You may freely copy, distribute and reuse the code in this example.
        NeXT disclaims any warranty of any kind, expressed or implied,
        as to its fitness for any particular use.
*/
#import "FlatFileAdaptor.h"
#import "FlatFileLoginPanel.h"

#import <AppKit/AppKit.h>

@interface FlatFileLoginPanel (NSTableDataSource)
- (int)numberOfRowsInTableView:(NSTableView *)tableView;
- (id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)column row:(int)rowIndex;
@end

#define Newline @"\n"
#define Tab     @"\t"

@implementation FlatFileLoginPanel

extern char *FlatFile_VERS_NUM[];

- init
{
    [super init];
    [NSBundle loadNibNamed:@"FlatFileLoginPanel" owner:self];

    [versionField setStringValue:[NSString stringWithFormat:[versionField stringValue], FlatFile_VERS_NUM]];
    return self;
}

- (void)dealloc
{
    [files release];
    [super dealloc];
}


- (NSDictionary *)runPanelForAdaptor:(EOAdaptor *)adaptor validate:(BOOL)validate
{
    NSDictionary *result;
    BOOL success;

    [self setConnectionDictionary:[adaptor connectionDictionary]];
    do {
        if ([NSApp runModalForWindow:[pathField window]] != NSRunContinuesResponse) {
            result = nil;
            [[pathField window] orderOut:nil];
            break;
        }
        result = [self connectionDictionary];
        [[pathField window] orderOut:nil];

        if (!validate) break;

        success = YES;
        [adaptor setConnectionDictionary:result];
        NS_DURING
            [adaptor assertConnectionDictionaryIsValid];
        NS_HANDLER
            NSRunAlertPanel (NULL, @"%@", NULL, NULL, NULL, [localException reason]);
            [self setConnectionDictionary:[adaptor connectionDictionary]];
            success = NO;
        NS_ENDHANDLER        
    } while (!success);

    return result;
}

- (void)cancel:sender
{
    [NSApp stopModalWithCode:NSRunAbortedResponse];
}

- (void)login:sender
{
    [NSApp stopModalWithCode:NSRunContinuesResponse];
}

- (NSString *)rootDirectoryFromPaths:(NSArray *)paths files:(NSArray **)filesP
{
    // given a list of paths return a directory and a list of files
    int count = [paths count];
    NSString *path;
    BOOL isDirectory;
    NSMutableArray *array;
    
    *filesP = nil;
    if (!count) return nil;

    // if they selected a directory, return all files in the directory
    path = [paths objectAtIndex:0];
    if ([[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:&isDirectory] && isDirectory)
    {
        *filesP = [[NSFileManager defaultManager] directoryContentsAtPath:path];
        return path;
    }

    // if they selected files, return the common directory
    *filesP = array = [NSMutableArray array];
    while (count--) {
        [array addObject:[[paths objectAtIndex:count] lastPathComponent]];
    }
    return [path stringByDeletingLastPathComponent];
}

- (void)setFiles:sender
{
    NSOpenPanel *openPanel = [NSOpenPanel openPanel];
    NSString *directory = [pathField stringValue];

    [openPanel setCanChooseDirectories:YES];
    [openPanel setCanChooseFiles:YES];
    [openPanel setAllowsMultipleSelection:YES];
    if (directory) [openPanel setDirectory:directory];
    if ([openPanel runModalForTypes:nil] != NSOKButton)
        return;

    [files autorelease];
    directory = [self rootDirectoryFromPaths:[openPanel filenames] files:&files];
    [files retain];

    [pathField setStringValue:directory];
    [fileTable reloadData];
}

- (void)removeFile:sender
{
    NSEnumerator *selectedRows = [fileTable selectedRowEnumerator];
    NSMutableArray *deadFiles = [NSMutableArray arrayWithCapacity:[files count]];
    NSNumber *rowIndex;

    while (rowIndex = [selectedRows nextObject])
        [deadFiles addObject:[files objectAtIndex:[rowIndex intValue]]];

    [files removeObjectsInArray:deadFiles];

    if (![files count]) {
        [pathField setStringValue:@""];
        [removeFileButton setEnabled:NO];
    }

    [fileTable reloadData];
}

- (void)setConnectionDictionary:(NSDictionary *)connectionInfo
{
    NSArray *fileList;
    NSString *path, *separator, *useHeadings;

    path = [connectionInfo objectForKey:FlatFilePathKey];
    if (!path)
        path = @"";

    [pathField setStringValue:path];

    [files autorelease];
    fileList = [connectionInfo objectForKey:FlatFileFilesKey];
    if (fileList && [fileList count])
        files = [[NSMutableArray alloc] initWithArray:fileList];
    else
        files = nil;

    [fileTable reloadData];

    separator = [connectionInfo objectForKey:FlatFileRowSeparatorKey];
    if (!separator)
        separator = @"";

    if ([separator isEqualToString:Newline])
        [rowSeparatorMatrix selectCellWithTag:0];
    else {
        [rowSeparatorField setStringValue:separator];
        [rowSeparatorMatrix selectCellWithTag:1];
    }

    separator = [connectionInfo objectForKey:FlatFileColumnSeparatorKey];
    if (!separator)
        separator = @"";

    if ([separator isEqualToString:Tab])
        [columnSeparatorMatrix selectCellWithTag:0];
    else {
        [columnSeparatorField setStringValue:separator];
        [columnSeparatorMatrix selectCellWithTag:1];
    }

    useHeadings = [connectionInfo objectForKey:FlatFileUseHeadersKey];
    [columnHeadingButton setState:[useHeadings isEqualToString:@"Y"]];    
}

- (NSDictionary *)connectionDictionary
{
    NSMutableDictionary *info;
    NSString *rowSeparator, *columnSeparator, *useHeadings, *path;
    
    info = [NSMutableDictionary dictionaryWithCapacity:5];

    path = [pathField stringValue];
    if (!path)
        path = @"";

    [info setObject:path forKey:FlatFilePathKey];

    if (files && [files count])
        [info setObject:files forKey:FlatFileFilesKey];

    if ([[rowSeparatorMatrix selectedCell] tag] == 0)
        rowSeparator = Newline;
    else {
        rowSeparator = [rowSeparatorField stringValue];
        if (!rowSeparator)
            rowSeparator = @"";
    }

    [info setObject:rowSeparator forKey:FlatFileRowSeparatorKey];

    if ([[columnSeparatorMatrix selectedCell] tag] == 0)
        columnSeparator = Tab;
    else {
        columnSeparator = [columnSeparatorField stringValue];
        if (!columnSeparator)
            columnSeparator = @"";
    }

    [info setObject:columnSeparator forKey:FlatFileColumnSeparatorKey];

    useHeadings = [columnHeadingButton state] ? @"Y" : @"N";
    [info setObject:useHeadings forKey:FlatFileUseHeadersKey];
    
    return info;
}

- (void)didChangeSelection:(NSTableView *)sender
{
    [removeFileButton setEnabled:([sender numberOfSelectedRows] != 0)];
}

- (int)numberOfRowsInTableView:(NSTableView *)tableView
{
    return [files count];
}

- (id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)column row:(int)rowIndex
{
    if ((rowIndex >= 0) && (rowIndex < [files count]))
        return [files objectAtIndex:rowIndex];

    return nil;
}

@end

