
#import "DiagnosticsPanel.h"

NSString *RunPrompt(NSString *title, NSString *pref)
{
    NSPanel *prompt;
    NSTextField *tfield;
    NSString *result = nil;
    
    NSView *sview;
    NSEnumerator *en;
    NSRect frame;

    prompt = NSGetAlertPanel(title, pref, @"OK", @"Cancel", nil);

    en = [[[prompt contentView] subviews] objectEnumerator];
    while((sview = [en nextObject])!=nil){
        if([sview isKindOfClass:[NSTextField class]] &&
           [[(NSTextField *)sview stringValue] isEqual:pref]){
            break;
        }
    }
    
    frame = [sview frame];
    tfield = [[NSTextField alloc] 
                 initWithFrame:
                     NSMakeRect(frame.origin.x+frame.size.width+20,
                                frame.origin.y,
                                240,
                                frame.size.height+5)];

    [[prompt contentView] addSubview:tfield];
    [prompt makeFirstResponder:tfield];
    [prompt makeKeyAndOrderFront:nil];

    [tfield performClick:nil];

    if([(id)prompt runModal]==NSAlertDefaultReturn){
        result = [[tfield stringValue] stringByTrimmingSpaces];
        if(result!=nil && [result isEqual:@""]==YES){
            result = nil;
        }
    }

    [tfield removeFromSuperview];
    NSReleaseAlertPanel(prompt);

    return result;
}

void ShowDiagnostics(NSString *title, NSString *diagnostics)
{
    NSApplication *app = [NSApplication sharedApplication];
    DiagnosticsPanel *dpanel;    

    NSWindow *mwin = [app modalWindow];
    if(mwin!=nil && 
       [mwin isKindOfClass:[DiagnosticsPanel class]]){
        dpanel = (DiagnosticsPanel *)mwin;

        [dpanel setTitle:title];
        [dpanel appendContent:diagnostics];

        return;
    }

    dpanel = 
        [[DiagnosticsPanel alloc]
            initWithTitle:title andContent:diagnostics];
    [app runModalForWindow:dpanel];
    [dpanel close];
}

@implementation DiagnosticsPanel

#define DGWIDTH 500

NSSize StringDimensions(NSString *str)
{
    NSSize result = { -1, 0 };

    NSEnumerator *en =  
        [[str componentsSeparatedByString:@"\n"]
            objectEnumerator];
    NSString *line;
    long len;

    while(line = [en nextObject]){
        result.height++;
        if((len = [line length])>result.width){
            result.width = len;
        }
    }

    return result;
}

- initWithTitle:(NSString *)title andContent:(NSString *)diagnostics
{
    int style =  NSTitledWindowMask | NSClosableWindowMask;

    NSView *contentView;
    NSButton *button;
    NSRect frame;

    NSFont *font = [NSFont userFixedPitchFontOfSize:12];
    
    textField = [[NSTextField alloc]
                    initWithFrame:
                        NSMakeRect(10, 250, DGWIDTH, 30)];
    [textField setFont:[NSFont labelFontOfSize:
                                   [[textField font] pointSize]+8]];
    [textField setStringValue:title];
    [textField setEditable:NO];
    [textField setBezeled: NO];
    [textField setDrawsBackground: NO];

    scrollView = [[NSScrollView alloc] 
                     initWithFrame:
                         NSMakeRect(10, 40, DGWIDTH, 200)];
    [scrollView setHasHorizontalScroller:YES];
    [scrollView setHasVerticalScroller:YES]; 

    NSString *content = diagnostics;
    if([diagnostics hasSuffix:@"\n"]==NO){
        content =
            [diagnostics stringByAppendingString:@"\n"];
    }

    fontDims = NSMakeSize([font boundingRectForFont].size.width,
                       [font defaultLineHeightForFont]);
    strDims = StringDimensions(content);

    textView = 
        [[NSTextView alloc] 
            initWithFrame:NSMakeRect(0, 0,
                                     strDims.width*fontDims.width, 
                                     strDims.height*fontDims.height)];
    [textView setBackgroundColor:[NSColor whiteColor]];
    
    [textView setString:content];
    [textView setFont:font];
    [textView setEditable:NO];

    [scrollView setDocumentView:textView];
    [scrollView setBorderType:NSLineBorder];

    button = [NSButton new];
    [button setTitle:@"Ok"];
    [button setKeyEquivalent: @"\r"];
    [button setImagePosition:NSImageRight];
    [button setImage:[NSImage imageNamed: @"common_ret"]];
    [button setAlternateImage:[NSImage imageNamed: @"common_retH"]];
    [button sizeToFit];

 
    frame = [button frame];
    [button setFrame:NSMakeRect(DGWIDTH+10-frame.size.width, 
                                10,
                                frame.size.width, 
                                frame.size.height)];

    [super
        initWithContentRect:
            NSMakeRect(0, 0, DGWIDTH+20, 300)
        styleMask:style
        backing:NSBackingStoreBuffered
        defer:NO];
    [super setReleasedWhenClosed:YES];
    [super setTitle:title];

    [button setTarget:self];
    [button setAction:@selector(done:)];
    
    contentView = [self contentView];
    [contentView addSubview:textField];
    [contentView addSubview:scrollView];
    [contentView addSubview:button];

    return self;
}


- (void)appendContent:(NSString *)diagnostics
{
    NSString *newContent = diagnostics;
    if([diagnostics hasSuffix:@"\n"]==NO){
        newContent =
            [diagnostics stringByAppendingString:@"\n"];
    }

    NSSize newDims = StringDimensions(newContent);

    strDims.width = 
        (strDims.width>newDims.width ? 
         strDims.width : newDims.width);
    strDims.height += newDims.height;
    
    NSRect newFrame =
        NSMakeRect(0, 0,
                   strDims.width*fontDims.width, 
                   strDims.height*fontDims.height);
    
    [[textView textContainer]
        setContainerSize:newFrame.size];
    [textView setFrame:newFrame];

    unsigned int len = [[textView string] length];
    [textView 
        replaceCharactersInRange:NSMakeRange(len, 0)
        withString:newContent];

    [scrollView display];
}

- (void)setTitle:(NSString *)newTitle
{
    [super setTitle:newTitle];
    [textField setStringValue:newTitle];

    return;
}

- done:(id)sender
{
    [[NSApplication sharedApplication]
        stopModal];
    return self;
}

@end
