/* Copyright (c) 2004, Noah Sorscher
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * 	¥ 	Redistributions of source code must retain the above copyright
 * 	notice, this list of conditions and the following disclaimer.
 * 	¥ 	Redistributions in binary form must reproduce the above copyright
 * 	notice, this list of conditions and the following disclaimer in the
 * 	documentation and/or other materials provided with the distribution.
 * 	¥ 	Neither the name of the Noah Sorscher nor the names of its
 * 	contributors may be used to endorse or promote products derived from
 * 	this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 * THE POSSIBILITY OF SUCH DAMAGE.
 */
#import "tMovieView.h"

@implementation tMovieView

- (void)setMovie:(id)movie
{
	if ([movie isKindOfClass:[QTMovie class]]) {
		[super setMovie:movie];
		return;
	}
	if ([movie isKindOfClass:[NSMovie class]]) {
		if ([movie respondsToSelector:@selector(qtKitMovie)]) {
			[super setMovie:[movie qtKitMovie]];
		}
	}
}

- (void)showController:(BOOL)show adjustingSize:(BOOL)adjustSize
{
	[super setControllerVisible:show];
}

- (float) rate
{
	return [[self movie] rate];
}

- (BOOL)isPlaying
{
	return [[self movie] rate] != 0;
}

- (void)setRate:(float)rate
{
	[[self movie] setRate:rate];
}

- (void)start:(id)sender
{
	[super play:sender];
}

- (void)stop:(id)sender
{
	[super pause:sender];
}

- (void) awakeFromNib
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(closeWindow:)  name:@"movieWindowCloseNotification" object:nil];
}

- (void) closeWindow:(NSNotification *)note
{
    //NSLog(@"close");
    [[self window] close];
}

- (BOOL)performKeyEquivalent:(NSEvent *)theEvent
{
    BOOL result;
    NSString *chars;
    unichar uch;
    
    result = [super performKeyEquivalent:theEvent];
    chars = [theEvent characters];
    uch = [chars characterAtIndex:0];
    if (uch == 'f') {
        [tPlayback fullScreen];
        return YES;
    }
    if (uch == '\t') {
        if ([theEvent modifierFlags] & NSAlternateKeyMask)
            [tPlayback lastMovie];
        else
            [tPlayback nextMovie];
        return YES;
    }
    if (uch == NSUpArrowFunctionKey || uch == NSDownArrowFunctionKey) {
        [tPlayback performSelector:@selector(refreshVolume:) withObject:nil afterDelay:0];
    }
    if ([theEvent modifierFlags] & NSCommandKeyMask ||
        [theEvent modifierFlags] & NSControlKeyMask) // ||
        //[theEvent modifierFlags] & NSAlternateKeyMask)
            return NO;
    BOOL forward = NO;
    switch (uch) {
        case NSRightArrowFunctionKey: forward = YES;
        case NSLeftArrowFunctionKey:
            if (doubles && [theEvent modifierFlags] & NSAlternateKeyMask) {
                MHMovie *movie = (MHMovie *)[[self movie] delegate];
                if ([movie isKindOfClass:[MHMovie class]]) {
                    double seconds = [movie currentTimeIndexSeconds];
                    if (forward) {
                        NSString *lang = nil;
                        if ([[movie chapters] multilingual]) lang = [movie currentLanguage];
                        seconds = [[movie chapters] nextTimeForTime:seconds language:lang];
                        if (seconds == -1) seconds = [movie durationSeconds] - 0.5;
                    } else
                        seconds = [[movie chapters] prevTimeForTime:seconds];
                    [movie setCurrentTimeIndexSeconds:seconds];
                } else return NO;
            } else if (doubles) {
                if (forward) [self stepForward:nil];
                else [self stepBack:nil];
            }
            doubles = !doubles;
            return YES;
        case 'f':
            [tPlayback fullScreen];
            return YES;
    }
    return [super performKeyEquivalent:theEvent];
}

- (void)mouseDown:(NSEvent *)event
{
    if ([event modifierFlags] & NSControlKeyMask)
        [self rightMouseDown:event];
    else [super mouseDown:event];
}

- (void)rightMouseDown:(NSEvent *)theEvent
{
    NSMenu *menu = [[[NSMenu alloc] init] autorelease];
    NSMenuItem *item = [[[NSMenuItem alloc] initWithTitle:@"Play" action:@selector(play:) keyEquivalent:@""] autorelease];
    [item setTarget:self];
    [menu addItem:item];
    item = [[[NSMenuItem alloc] initWithTitle:@"Stop" action:@selector(pause:) keyEquivalent:@""] autorelease];
    [item setTarget:self];
    [menu addItem:item];
    NSString *title = @"Show Controller";
    if ([self isControllerVisible])
	title = @"Hide Controller";
    item = [[[NSMenuItem alloc] initWithTitle:title action:@selector(toggleController:) keyEquivalent:@""] autorelease];
    [item setTarget:[tPlayback nibInstance]];
    [menu addItem:item];
	NSArray *tracks = [[[self movie] delegate] tracksOfType:@"Sound"];
	int i, n = [tracks count];
	if (n > 1) {
		NSMenu *submenu = [[[NSMenu alloc] init] autorelease];
		item = [[[NSMenuItem alloc] initWithTitle:@"Language" action:nil keyEquivalent:@""] autorelease];
		[item setSubmenu:submenu];
		[menu addItem:item];
		for (i=0;i<n;i++) {
			MHTrack *track = [tracks objectAtIndex:i];
			NSString *name = [track name];
			if (!name) name = [NSString stringWithFormat:@"Sound Track %d", i+1];
			item = [[[NSMenuItem alloc] initWithTitle:name action:@selector(setSoundTrack:) keyEquivalent:@""] autorelease];
			if ([track enabled]) [item setState:YES];
			[item setTarget:[tPlayback nibInstance]];
			[submenu addItem:item];
		}
	}
	
    if ([[[self movie] delegate] respondsToSelector:@selector(chapters)] && [(MHChapters *)[(MHMovie *)[[self movie] delegate] chapters] count]) {
		NSMenu *submenu = [[[NSMenu alloc] init] autorelease];
		item = [[[NSMenuItem alloc] initWithTitle:@"Chapters" action:nil keyEquivalent:@""] autorelease];
		[item setSubmenu:submenu];
		[menu addItem:item];
		NSString *lang = nil;
		if ([[(MHMovie *)[[self movie] delegate] chapters] multilingual]) lang = [(MHMovie *)[[self movie] delegate] currentLanguage];
		NSArray *names = [[(MHMovie *)[[self movie] delegate] chapters] chapterNamesForLanguage:lang];
		n = [names count];
		for (i=0;i<n;i++) {
			item = [[[NSMenuItem alloc] initWithTitle:[names objectAtIndex:i] action:@selector(gotoChapter:) keyEquivalent:@""] autorelease];
			[item setTarget:[tPlayback nibInstance]];
			[submenu addItem:item];
		}
    }
    
    [NSMenu popUpContextMenu:menu withEvent:theEvent forView:self];
}

@end
