#import "DemoView.h"

@implementation DemoView

- (id)initWithFrame:(NSRect)frameRect
{
	if ((self = [super initWithFrame:frameRect]) != nil) 
	{
		// Add initialization code here
	}
	
	return self;
}

- (void) dealloc
{
	[filter release];
	[context release];
	[src release];
	
	[super dealloc];
}

- (void)drawRect:(NSRect)rect
{
	[super drawRect: rect];
	
	if ( context == nil ) 
	{ 
		context = [CIContext contextWithCGContext: [[NSGraphicsContext currentContext] graphicsPort] options: nil]; 
			
		[context retain]; 
	} 
		
	if ( src != nil )
	{
		if ( filter == nil )
		{
			filter = [CIFilter filterWithName: @"CIHueAdjust"];
			
			if ( filter == nil )
				NSRunAlertPanel ( @"Error", @"Cannot create CIFilter", @"OK", nil, nil );

			[filter retain];
			[filter setDefaults];
			[filter setValue: src forKey: @"inputImage"];
			[filter setValue: [NSNumber numberWithFloat: -0.5] forKey: @"inputAngle"];		
		}
		
		CGRect	extent = [src extent];
		
		res = [filter valueForKey: @"outputImage"];
		
		if ( res == nil )
			NSRunAlertPanel ( @"Error", @"res is nil", @"OK", nil, nil );

		[context drawImage: res atPoint: extent.origin fromRect: extent ];
	}
}

- (IBAction) open: (id)sender
{
	NSOpenPanel * panel = [NSOpenPanel openPanel];
	NSArray     * types = [NSArray arrayWithObjects: @"tiff", @"png", @"tga", @"gif", @"jpg", @"bmp", nil];
	
	[panel beginSheetForDirectory: @"" file: nil types: types modalForWindow: [self window] modalDelegate: self 
	       didEndSelector: @selector (openPanelDidEnd:returnCode:contextInfo:) contextInfo: nil];
}

- (void) openPanelDidEnd: (NSOpenPanel *) panel returnCode: (int) returnCode contextInfo: (void  *) contextInfo
{
	if ( returnCode !=  NSOKButton )
		return;
	NSString * path  = [panel filename];
	NSURL    * url   = [NSURL fileURLWithPath: path];
	CIImage  * img   = [CIImage imageWithContentsOfURL: url];
	
	if ( img == nil )
	{
		NSRunAlertPanel ( @"Error", @"Cannot create CIImage from file", @"OK", nil, nil );
		
		return;
	}
	
	[src autorelease];
	
	src = [img retain];
	
	CGRect	content =  [img extent];
	NSSize	imgSize = NSMakeSize ( CGRectGetWidth ( content ), CGRectGetHeight ( content ) );
	
	if ( imgSize.width < 250 )
		imgSize.width = 250;
	
	[[self window] setContentSize: NSMakeSize ( imgSize.width + 40, imgSize.height + 358 - 293 )];
	[[self window] setTitleWithRepresentedFilename: path];
	
	[filter setValue: src forKey: @"inputImage"];
	[self setNeedsDisplay: YES];
}

- (IBAction)setAmount:(id)sender
{
	float	angle = [sender floatValue];
	
	[filter setValue: [NSNumber numberWithFloat: angle] forKey: @"inputAngle"];
	[self setNeedsDisplay: YES];
}

@end
