//
//  FormPrompter.m
//  longspear
//
//  Created by Niko Matsakis on Sat Nov 15 2003.
//  Copyright (c) 2003 __MyCompanyName__. All rights reserved.
//

#import "FormPrompter.h"
#import "NSFormExtensions.h"


@implementation FormPrompter

+ (void) promptForItems:(NSArray*)items target:target selector:(SEL)whenadded window:(NSWindow*)win;
{
  // Create the FormPrompter object
  FormPrompter *newprompt = 
    [[FormPrompter alloc] initWithTarget:target selector:whenadded];
  [NSBundle loadNibNamed:@"FormPrompter" owner:newprompt];
  
  // Set up the form to have one entry for each item
  [newprompt prepareFormWithItems:items];
  
  // Attach the sheet
  [NSApp beginSheet: newprompt->_window
         modalForWindow: win
         modalDelegate: nil
         didEndSelector: nil
         contextInfo: nil]; 
  [NSApp runModalForWindow: newprompt->_window]; 

  // (The app is running modally here.  When the Add or Don't Add are clicked,
  // the modal session will end.)

  // Once it's over...
  [NSApp endSheet:newprompt->_window];
  [newprompt->_window orderOut:self];
  [newprompt release];
}

- initWithTarget:target selector:(SEL)whenadded
{
  if ((self = [super init])) {
      _target = target;
      _whenAdded = whenadded;
  }
  return self;
}

- (IBAction) add:sender
{
    [_target performSelector:_whenAdded withObject:[_form valuesAsDictionary]];
    [NSApp stopModal];
}

- (IBAction) dontAdd:sender
{
    [NSApp stopModal];
}

- (void) prepareFormWithItems:(NSArray*)items
{
    NSSize winsize = [_window contentMinSize];
    NSSize cellsize;

    // form always begins with one dummy entry, delete it
    [_form removeEntryAtIndex:0];
    
    // add one entry for each item
    NSEnumerator *itemsenum = [items objectEnumerator];
    id item;
    while ((item = [itemsenum nextObject])) {
        NSFormCell *fcell = [_form addEntry:[NSString stringWithFormat:@"%@:", item]];
        cellsize = [fcell cellSize];
    }
    
    int itemcnt = [items count];
    if (itemcnt > 0) {
        float reqsize = cellsize.height * itemcnt; 
    
        // we need to resize the window to account for the form
        winsize.height += reqsize - cellsize.height;  // already had one row built in
        [_window setContentSize:winsize];
        NSLog (@"FormPrompter reqsize=%f itemcnt=%d matrixrow=%d\n",
               reqsize, itemcnt, [_form numberOfRows]);
        NSRect frame = [_form bounds];
        NSLog (@"FormPrompter form bounds=(%f,%f)x(%f,%f)",
               frame.origin.x, frame.origin.y, frame.size.width, frame.size.height);
        [_form sizeToCells];
        frame = [_form bounds];
        NSLog (@"FormPrompter form bounds=(%f,%f)x(%f,%f)",
               frame.origin.x, frame.origin.y, frame.size.width, frame.size.height);
    }
}

@end
