/*
SRFullScreenController.m

Author: Makoto Kinoshita

Copyright 2004-2006 The Shiira Project. All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted 
provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions 
  and the following disclaimer.

  2. 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.

THIS SOFTWARE IS PROVIDED BY THE SHIIRA PROJECT ``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 SHIIRA PROJECT 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 "SRBrowserController.h"
#import "SRFullScreenController.h"

#import "SRFullScreenWindow.h"

#import "HMWindow.h"

static int  _SRFullScreenControlHeight = 110;

@implementation SRFullScreenController

//--------------------------------------------------------------//
#pragma mark -- Initialize --
//--------------------------------------------------------------//

- (id)init
{
    self = [super initWithWindowNibName:@"FullScreen"];
    if (!self) {
        return nil;
    }
    
    // Initialize instance variables
    
    return self;
}

- (void)windowDidLoad
{
    // Configure window
    NSWindow*   window;
    window = [self window];
    [window setOpaque:NO];
    [window setLevel:NSFloatingWindowLevel];
    [window setHasShadow:NO];
    
    // Set content view
    NSView*                     oldView;
    SRFullScreenControlView*    contentView;
    oldView = [window contentView];
    contentView = [[SRFullScreenControlView alloc] initWithFrame:[oldView frame]];
    
    NSEnumerator*   enumerator;
    NSView*         subview;
    enumerator = [[oldView subviews] objectEnumerator];
    while (subview = [enumerator nextObject]) {
        [subview removeFromSuperview];
        [contentView addSubview:subview];
    }
    
    [window setContentView:contentView];
    [contentView release];
}

- (void)dealloc
{
    if ([_displayTimer isValid]) {
        [_displayTimer invalidate];
    }
    _displayTimer = nil;
    
    if ([_fadeOutTimer isValid]) {
        [_fadeOutTimer invalidate];
    }
    _fadeOutTimer = nil;
    
    [super dealloc];
}

//--------------------------------------------------------------//
#pragma mark -- Controllers --
//--------------------------------------------------------------//

- (SRBrowserController*)browserController
{
    return _browserController;
}

- (void)setBrowserController:(SRBrowserController*)browserController
{
    _browserController = browserController;
}

//--------------------------------------------------------------//
#pragma mark -- Web view --
//--------------------------------------------------------------//

- (WebView*)webView
{
    return [[_browserController selectedPageController] webView];
}

//--------------------------------------------------------------//
#pragma mark -- Fade out timer handling --
//--------------------------------------------------------------//

- (void)restartDisplayTimer
{
    // Cancel timers
    if ([_displayTimer isValid]) {
        [_displayTimer invalidate];
    }
    _displayTimer = nil;
    
    if ([_fadeOutTimer isValid]) {
        [_fadeOutTimer invalidate];
    }
    _fadeOutTimer = nil;
    
    // Show window
    NSWindow*   window;
    window = [self window];
    [window setAlphaValue:1.0f];
    [window orderFront:self];
    
    // Start display timer
    _displayTimer = [NSTimer scheduledTimerWithTimeInterval:3.0f 
            target:self selector:@selector(displayTimerFired:) userInfo:nil repeats:NO];
}

- (void)cancelTimer
{
    // Cancel timers
    if ([_displayTimer isValid]) {
        [_displayTimer invalidate];
    }
    _displayTimer = nil;
    
    if ([_fadeOutTimer isValid]) {
        [_fadeOutTimer invalidate];
    }
    _fadeOutTimer = nil;
    
    // Set window alpha
    NSWindow*   window;
    window = [self window];
    [window setAlphaValue:1.0f];
}

- (void)displayTimerFired:(NSTimer*)timer
{
    // Invalidate display timer
    _displayTimer = nil;
    
    // Start fade out timer
    _fadeOutTimer = [NSTimer scheduledTimerWithTimeInterval:0.05f 
            target:self selector:@selector(fadeOutTimerFired:) userInfo:nil repeats:YES];
}

- (void)fadeOutTimerFired:(NSTimer*)timer
{
    // Fade out window
    NSWindow*   window;
    float       alpha;
    window = [self window];
    alpha = [window alphaValue];
    
    alpha -= 0.1f;
    if (alpha < 0.0f) {
        alpha = 0.0f;
    }
    [window setAlphaValue:alpha];
    
    // Stop fade out timer and close window
    if (alpha == 0.0f) {
        [window orderOut:self];
        
        if ([_fadeOutTimer isValid]) {
            [_fadeOutTimer invalidate];
        }
        _fadeOutTimer = nil;
    }
}

- (void)startAppearingTimer
{
}

- (void)startDisappearingTimer
{
}

//--------------------------------------------------------------//
#pragma mark -- Wokring with full screen mode --
//--------------------------------------------------------------//

- (void)backToNormalMode
{
    // Close window
    NSWindow*   window;
    window = [self window];
    [window orderOut:self];
    
    // Cancel timers
    [self cancelTimer];
}

//--------------------------------------------------------------//
#pragma mark -- Actions --
//--------------------------------------------------------------//

- (void)goBackAction:(id)sender
{
    [_browserController goBackAction:sender];
}

- (void)goForwardAction:(id)sender
{
    [_browserController goForwardAction:sender];
}

- (void)reloadPageAction:(id)sender
{
    [_browserController reloadPageAction:sender];
}

- (void)stopLoadingAction:(id)sender
{
    [_browserController stopLoadingAction:sender];
}

- (void)smallerTextAction:(id)sender
{
    [_browserController smallerTextAction:sender];
}

- (void)biggerTextAction:(id)sender
{
    [_browserController biggerTextAction:sender];
}

- (void)backToNormalModeAction:(id)sender
{
    [_browserController backToNormalModeAction:sender];
}

//--------------------------------------------------------------//
#pragma mark -- NSWindowController override --
//--------------------------------------------------------------//

- (void)showWindow:(id)sender
{
//    [self restartDisplayTimer];
    
    [super showWindow:sender];
}

//--------------------------------------------------------------//
#pragma mark -- HMWindow delegate --
//--------------------------------------------------------------//

- (void)_startUppaerAppearingAnimation
{
    // Get screen frame
    NSRect  screenFrame;
    screenFrame = [[[_browserController window] screen] frame];
    
    // Get window
    NSWindow*   window;
    window = [self window];
    
    // Deicde start and end frame
    NSRect  startFrame, endFrame;
    endFrame = [window frame];
    endFrame.origin.x = (screenFrame.size.width - endFrame.size.width) / 2.0f;
    endFrame.origin.y = screenFrame.size.height - endFrame.size.height - 24.0f;
    
    startFrame = [window frame];
    startFrame.origin.x = endFrame.origin.x;
    startFrame.origin.y = screenFrame.size.height + startFrame.size.height;
    
    [window setFrame:startFrame display:YES];
    [self showWindow:self];
    
    // Start animation
    NSDictionary*   dict;
    dict = [NSDictionary dictionaryWithObjectsAndKeys:
            [NSValue valueWithRect:startFrame], NSViewAnimationStartFrameKey, 
            [NSValue valueWithRect:endFrame], NSViewAnimationEndFrameKey, 
            window, NSViewAnimationTargetKey, 
            nil];
    _animation = [[NSViewAnimation alloc] 
            initWithViewAnimations:[NSArray arrayWithObject:dict]];
    [_animation setDuration:0.3f];
    [_animation setAnimationCurve:NSAnimationEaseIn];
    [_animation setAnimationCurve:NSAnimationNonblocking];
    [_animation setDelegate:self];
    [_animation startAnimation];
}

- (void)_startLowerAppearingAnimation
{
    // Get screen frame
    NSRect  screenFrame;
    screenFrame = [[[_browserController window] screen] frame];
    
    // Get window
    NSWindow*   window;
    window = [self window];
        
    // Deicde start and end frame
    NSRect  startFrame, endFrame;
    endFrame = [window frame];
    endFrame.origin.x = (screenFrame.size.width - endFrame.size.width) / 2.0f;
    endFrame.origin.y = 24.0f;
    
    startFrame = [window frame];
    startFrame.origin.x = endFrame.origin.x;
    startFrame.origin.y = -1 * startFrame.size.height;
    
    [window setFrame:startFrame display:YES];
    [self showWindow:self];
    
    // Start animation
    NSDictionary*   dict;
    dict = [NSDictionary dictionaryWithObjectsAndKeys:
            [NSValue valueWithRect:startFrame], NSViewAnimationStartFrameKey, 
            [NSValue valueWithRect:endFrame], NSViewAnimationEndFrameKey, 
            window, NSViewAnimationTargetKey, 
            nil];
    _animation = [[NSViewAnimation alloc] 
            initWithViewAnimations:[NSArray arrayWithObject:dict]];
    [_animation setDuration:0.3f];
    [_animation setAnimationCurve:NSAnimationEaseIn];
    [_animation setAnimationCurve:NSAnimationNonblocking];
    [_animation setDelegate:self];
    [_animation startAnimation];
}

- (void)hmWindow:(NSWindow*)window mouseMoved:(NSEvent*)event
{
    // Calc bounds for control window
    NSRect  screenFrame;
    NSRect  upperBounds, lowerBounds;
    screenFrame = [[window screen] frame];
    upperBounds.origin.x = screenFrame.origin.x;
    upperBounds.origin.y = screenFrame.origin.y + screenFrame.size.height - _SRFullScreenControlHeight;
    upperBounds.size.width = screenFrame.size.width;
    upperBounds.size.height = _SRFullScreenControlHeight + 1;
    lowerBounds.origin.x = screenFrame.origin.x;
    lowerBounds.origin.y = screenFrame.origin.y;
    lowerBounds.size.width = screenFrame.size.width;
    lowerBounds.size.height = _SRFullScreenControlHeight;
    
    // Check mouse location
    NSPoint point;
    point = [event locationInWindow];
    if (NSPointInRect(point, upperBounds)) {
        if (!_animation && ![[self window] isVisible]) {
            [self _startUppaerAppearingAnimation];
        }
    }
    else if (NSPointInRect(point, lowerBounds)) {
        if (!_animation && ![[self window] isVisible]) {
            [self _startLowerAppearingAnimation];
        }
    }
    else {
        // Hide window
        [[self window] orderOut:self];
    }
}

//--------------------------------------------------------------//
#pragma mark -- NSAnimation delegate --
//--------------------------------------------------------------//

- (void)animationDidEnd:(NSAnimation*)animation
{
    [_animation release], _animation = nil;
}

- (void)animationDidStop:(NSAnimation*)animation
{
}

//--------------------------------------------------------------//
#pragma mark -- SRFullScreenControlWindow delegate --
//--------------------------------------------------------------//

- (void)window:(NSWindow*)window mouseDown:(NSEvent*)event
{
    // Cancel timer
    [self cancelTimer];
}

- (void)window:(NSWindow*)window mouseUp:(NSEvent*)event
{
    // Restart timer
    [self restartDisplayTimer];
}

@end
