//
//  MVerticalLayoutView.m
//  MySQLWorkbench
//
//  Created by Alfredo Kojima on 17/Dec/08.
//  Copyright 2008 Sun Microsystems Inc. All rights reserved.
//

// Layout contained views vertically. Width of subviews will be adjusted to the same as parent
// Height will be taken from the subviews themselves. Will resize to fit the height of all subviews.

#import "MVerticalLayoutView.h"


@implementation MVerticalLayoutView

- (void) dealloc
{
  [[NSNotificationCenter defaultCenter] removeObserver:self];
  [super dealloc];
}


- (BOOL)isFlipped
{
  return YES;
}

- (void)setSpacing:(float)spc
{
  spacing= spc;
  [self relayout];
}

- (void)setPadding:(float)spc
{
  padding= spc;
  [self relayout];
}

- (void)relayout
{
  float availableHeight;
  float y;
  float oldUsedHeight= usedHeight;
  
  if (relayouting)
    return;
  relayouting= YES;
  
  usedHeight= spacing * ([[self subviews] count]-1) + padding * 2;
  for (NSView *view in [self subviews])
    usedHeight+= NSHeight([view frame]);
  
  if (oldUsedHeight == usedHeight)
  {
    relayouting= NO;
    return;
  }
  availableHeight= NSHeight([[self superview] frame]);
  
  [self setFrameSize:NSMakeSize(NSWidth([self frame]), usedHeight < availableHeight ? availableHeight : usedHeight)];
//  [self setFrameSize:NSMakeSize(NSWidth([self frame]), usedHeight)];
  
  y= padding;
  for (NSView *view in [self subviews])
  {
    [view setFrameOrigin:NSMakePoint(0, y)];
    y+= NSHeight([view frame]) + spacing;
  }
  
  [self setNeedsDisplay:YES];
  
  relayouting= NO;
}


- (void)resizeWithOldSuperviewSize:(NSSize)oldBoundsSize
{
  // resize to the same size as the superview, but not smaller than we can
  NSSize superSize= [[self superview] frame].size;
  NSRect frame= [self frame];
  
  frame.size.width= superSize.width;
  if (usedHeight > superSize.height)
    frame.size.height= usedHeight;
  else
    frame.size.height= superSize.height;
  
  [self setFrame: frame];
  [self relayout];
}


- (void)childFrameChanged:(NSNotification*)notif
{
  [self relayout];
}


- (void)didAddSubview:(NSView*)subview
{
  [subview setPostsFrameChangedNotifications:YES];
  [[NSNotificationCenter defaultCenter] addObserver:self
                                           selector:@selector(childFrameChanged:)
                                               name:NSViewFrameDidChangeNotification
                                             object:subview];
  
  [super didAddSubview:subview];
  
  [self relayout];
}


- (void)setBackgroundColor:(NSColor*)color
{
  [backColor autorelease];
  backColor= [color retain];
}


- (void)drawRect:(NSRect)rect
{
  if (backColor)
  {
    [backColor set];
    NSRectFill(rect);
  }
}

@end
