/*
 * PhotoSlideshow.j
 *
 * Created by Philippe Laval on 2009/03/19.
 * Copyright 2009 Philippe Laval. All rights reserved.
 */

@import <AppKit/CPWindowController.j>


@implementation PhotoSlideshow : CPWindowController
{
	CPImageView imageView;
}

- (id)init
{
	// Determine the size of the window
	var application = [CPApplication sharedApplication];
	
	var aContentRect = CPRectCreateCopy([[application mainWindow] frame]);
	aContentRect = CGRectInset(aContentRect, 10, 10);
	
	// Create the window 
    var theWindow = [[CPWindow alloc] initWithContentRect:aContentRect
    						styleMask:CPHUDBackgroundWindowMask | CPClosableWindowMask | CPResizableWindowMask]; // CPTexturedBackgroundWindowMask
        
    // Now we can use the designed initializer (a little trick)
    self = [super initWithWindow:theWindow];
    if (self)
    {
        [theWindow setTitle:@"Slide Show"];
        [theWindow setDelegate:self];
        
        var contentView = [theWindow contentView];
        
        // Populate the content of the window

		imageView = [[CPImageView alloc] initWithFrame:CGRectMake(10, 10, CGRectGetWidth([contentView bounds]) - 20, CGRectGetHeight([contentView bounds]) - 20)];
		[imageView setHasShadow:YES];
		[imageView setImageScaling:CPScaleProportionally];
		[imageView setAutoresizingMask:CPViewWidthSizable | CPViewHeightSizable];

		[contentView addSubview:imageView];
    }
    
    return self;
}



-(void)switchImage:(CPTimer)aTimer
{	
	var dict = [aTimer userInfo];
	var currentIndex = [[dict objectForKey:@"currentIndex"] longValue];
	var paths = [dict objectForKey:@"images"];
	
	var path = [paths objectAtIndex:currentIndex];
	var image = [[CPImage alloc] initWithContentsOfFile:path];
    [image setDelegate:self];

	// Verify that the image is loaded. 
	// If it is not, it will be associated with the imageView by the image delegate method imageDidLoad:
    if([image loadStatus] == CPImageLoadStatusCompleted)
        [imageView setImage:image];
    else
        [imageView setImage:nil];

	currentIndex++;
	
	if (currentIndex >= [paths count])
	{
		debugger;
		
		currentIndex = 0;
	}
	[dict setObject:[CPNumber numberWithLong:currentIndex] forKey:@"currentIndex"];
    
}

// Called since we have marked ouself to be the image delegate
- (void)imageDidLoad:(CPImage)anImage
{
	//debugger;
    [imageView setImage:anImage];
}



// Close the window when the user click the "esc" key
-(void) keyDown:(CPEvent)anEvent
{
	// The user cliked on the "esc" key
	if ([anEvent keyCode] == 27)
	{
		// debugger;
		
		// This will result in windowWillClose: been called (we stop the modal loop there)
		[[self window] close];
	}
	
}

// Called when the user close the window (by clicking on the close button)
- (void)windowWillClose:(id)aSender
{
	// debugger;

	// Stop the modal loop
	var application = [CPApplication sharedApplication];
	[application stopModal];
}

@end