#import "MovieView.h"

@implementation MovieView

- initWithFrame:(NSRect)r
{
    self = [super initWithFrame:r];
    if (self == nil)
        return nil;

    framesPerSecond = 10;
    direction = 1;
    [self updatePositionControl];
    
    return self;
}

- (void)play:(id)sender
{
    [timer invalidate];
    [timer autorelease];
    timer = [[NSTimer scheduledTimerWithTimeInterval:1.0 / framesPerSecond
                                    target:self
                                  selector:@selector(animate:)
                                    userInfo:nil
                                   repeats:YES] retain]; 
}

- (void)positionControlChanged:(id)sender
{
    currentFrameIndex = [sender floatValue] * [frames count];
    [self setNeedsDisplay:YES];
}

- (void)setFrames:(id)obj
{
    [frames autorelease];
    frames = [obj retain];
}

- (void)speedControlChanged:(id)sender
{
    BOOL wasRunning = [timer isValid];
    
    framesPerSecond = [speedControl floatValue];
    [self stop:nil];
    if (wasRunning)
        [self play:nil];
}

- (void)rewind:sender
{
    currentFrameIndex -= 5;
    [self updatePositionControl];
    [self setNeedsDisplay:YES];
}

- (void)fastForward:sender
{
    currentFrameIndex += 5;
    [self updatePositionControl];
    [self setNeedsDisplay:YES];
}

- (void)stepBackward:(id)sender
{
    --currentFrameIndex;
    [self updatePositionControl];
    [self setNeedsDisplay:YES];
}

- (void)stepForward:(id)sender
{
    ++currentFrameIndex;
    [self updatePositionControl];
    [self setNeedsDisplay:YES];
}

- (void)stop:(id)sender
{
    [timer invalidate];
    [self setNeedsDisplay:YES];
}

- (void)drawRect:(NSRect)rect
{
    currentFrameIndex = MIN (currentFrameIndex, [frames count] - 1);
    currentFrameIndex = MAX (currentFrameIndex, 0);

    if ([frames count] > 0)
    {
        NSImage *image = [frames objectAtIndex:currentFrameIndex];
        [image compositeToPoint:NSZeroPoint operation:NSCompositeCopy];
    }
}

- (void)animate:(id)userInfo
{
    currentFrameIndex += direction;
    if (currentFrameIndex < 0)
    {
        direction = 1;
        currentFrameIndex = 1;
    }
    else if (currentFrameIndex >= [frames count])
    {
        direction = -1;
        currentFrameIndex = [frames count] - 2;
    }
    
    [self updatePositionControl];
    [self setNeedsDisplay:YES];
}

-(void)updatePositionControl
{
    [positionControl setFloatValue:currentFrameIndex / (float)([frames count] - 1.0)];
}
@end
