//
//  MPT_AutoTileView.m
//  AUCoderDemo
//
//  Created by Andrew Salamon on 10/23/06.
//  Copyright 2006 Machine Perception Laboratory, University of California San Diego.. All rights reserved.
//

#import "MPT_AutoTileView.h"
#import "MPT_AUView.h"

static const float margin = 8.0;
static const NSRect baseRect = { 0.0, 0.0, 200.0, 65.0 };

@interface MPT_AutoTileView(PrivateMethods)
- (NSRect)frameForView:(MPT_AUView *)view;
@end

@implementation MPT_AutoTileView

- (id)initWithFrame:(NSRect)frame
{
    if( self = [super initWithFrame:frame] )
	{
        // Initialization code here.
		views = [[NSMutableArray alloc] init];
		
		slot.col = 0;
		slot.row = 0;
		maxSlot.col = 20;
		maxSlot.row = [self maxRowsForCurrentHeight];
    }
    return self;
}

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

//- (void)drawRect:(NSRect)rect
//{
//    // Drawing code here.
//	NSFrameRect([self bounds]);
//	[super drawRect:rect];
//}

//- (void)resizeSubviewsWithOldSize:(NSSize)oldSize
//{
//	int newMax = [self maxRowsForCurrentHeight];
//	if( newMax != maxSlot.row )
//	{
//		maxSlot.row = newMax;
//		[self tileViews];
//	}
//	[super resizeSubviewsWithOldSize:oldSize];
//}

- (void)setFrameSize:(NSSize)newSize
{
	[super setFrameSize:newSize];
	
	int newMax = [self maxRowsForCurrentHeight];
	if( newMax != maxSlot.row )
	{
		maxSlot.row = newMax;
		[self tileViews];
	}
}

- (BOOL)isFlipped
{
	return YES;
}

- (void)addView:(MPT_AUView *)view
{
	if( ![views containsObject:view] )
	{
		[views addObject:view];
	}
}
- (void)removeView:(MPT_AUView *)view
{
//	[views removeObject:view];
	[view removeFromSuperview];
}

- (void)tileViews
{
	NSEnumerator *viewEnum = [views objectEnumerator];
	MPT_AUView *view;

	slot.col = 0;
	slot.row = 0;

	while( view = [viewEnum nextObject] )
	{
		if( [view isEnabled] )
		{
			[view setFrame:[self frameForView:view]];
			[view setAutoresizingMask:NSViewMaxXMargin|NSViewMaxYMargin];
			if( [view superview] != self )
			{
				if( [view superview] )
					[view removeFromSuperview];
				[self addSubview:view];
			}
		}
		else
		{
			[view removeFromSuperview];
		}
	}
	
	[self setNeedsDisplay:YES];
}

- (NSRect)frameForView:(MPT_AUView *)view
{
	NSPoint origin = { 0.0, 0.0 };
	NSRect viewRect = baseRect;
		
	origin.x += (baseRect.size.width + margin) * slot.col;
	origin.y += (baseRect.size.height + margin) * slot.row;
	
	viewRect.origin = origin;
	
	++slot.row;
	if( slot.row >= maxSlot.row )
	{
		slot.row = 0;
		++slot.col;
	}
	
	return viewRect;
}

- (int)maxRowsForCurrentHeight
{
	float height = [self frame].size.height;
	float viewHeight = 0.0;
	int rows = 0;
	
	while( viewHeight < height )
	{
		viewHeight += baseRect.size.height;
		if( viewHeight <= height )
			++rows;
		viewHeight += margin;
	}
	
	return rows;
}
@end
