/*
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 "SRPageController.h"

#import "SRFullScreenWindow.h"
#import "SRURLCompleteDataSource.h"

static int  _SRFullScreenControlHeight = 110;

@interface SRFullScreenController (private)
// WebView notification
- (void)progressFinished:(NSNotification*)notification;
@end

@implementation SRFullScreenController

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

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

- (void)windowDidLoad
{
    // Configure window
    NSWindow*   window;
    window = [self window];
    [window setOpaque:NO];
    [window setLevel:NSFloatingWindowLevel];
    [window setAcceptsMouseMovedEvents:YES];
    
    // Configure url text field
    [_urlComboBox setFont:[NSFont systemFontOfSize:[NSFont smallSystemFontSize]]];
    [[_urlComboBox cell] setSendsActionOnEndEditing:NO];
    [_urlComboBox setCompletes:YES];
    [_urlComboBox setDelegate:self];
    [_urlComboBox setTarget:self];
    [_urlComboBox setAction:@selector(openLocationAction:)];
    [_urlComboBox setUsesDataSource:YES];
    [_urlComboBox setDataSource:_urlDataSource];
    
    // 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];
        
        if ([subview isKindOfClass:[NSButton class]]) {
            [subview setFocusRingType:NSFocusRingTypeNone];
        }
    }
    
    [window setContentView:contentView];
    [contentView release];
    
    // Configure progress window
    [_progressWindow setOpaque:NO];
    [_progressWindow setLevel:NSFloatingWindowLevel];
    
    // Set progress content view
    SRFullScreenProgressView*   progressCcontentView;
    oldView = [_progressWindow contentView];
    progressCcontentView = [[SRFullScreenProgressView alloc] initWithFrame:[oldView frame]];
    
    enumerator = [[oldView subviews] objectEnumerator];
    while (subview = [enumerator nextObject]) {
        [subview removeFromSuperview];
        [progressCcontentView addSubview:subview];
    }
    
    [_progressWindow setContentView:progressCcontentView];
    [progressCcontentView release];
}

- (void)dealloc
{
    [_urlDataSource release], _urlDataSource = nil;
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    [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];
}

- (void)_updateControlView
{
    // Get title
    WebDataSource*  dataSource;
    NSString*       title = nil;
    dataSource = [[[self webView] mainFrame] dataSource];
    if (dataSource) {
        title = [dataSource pageTitle];
    }
    if (!title) {
        title = @"";
    }
    
    // Set title
    [_titleTextField setStringValue:title];
    
    // Get URL
    NSString*   urlString;
    urlString = [[[dataSource request] URL] absoluteString];
    if (!urlString) {
        urlString = @"";
    }
    
    // Set URL
    [_urlComboBox setStringValue:urlString];
}

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

- (void)goToFullScreenMode
{
    // Register notifications
    WebView*                webView;
    NSNotificationCenter*   center;
    webView = [self webView];
    center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(progressStarted:) 
            name:WebViewProgressStartedNotification object:webView];
    [center addObserver:self selector:@selector(progressFinished:) 
            name:WebViewProgressFinishedNotification object:webView];
    
    SRPageController*   pageController;
    pageController = [_browserController selectedPageController];
    [center addObserver:self selector:@selector(pageDidCommitLoad:) 
            name:SRPageDidCommitLoad object:pageController];
    [center addObserver:self selector:@selector(pageTitleReceived:) 
            name:SRPageTitleReceived object:pageController];
}

- (void)backToNormalMode
{
    // Close window
    NSWindow*   window;
    window = [self window];
    [window orderOut:self];
    
    // Remove observer
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    // Hide progress window
    [self progressFinished:nil];
}

//--------------------------------------------------------------//
#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)openLocationAction:(id)sender
{
    // Get string
    NSString*   string;
    string = [sender stringValue];
    
    // Get URL string from combo box
    NSString*   urlString;
    urlString = [[sender dataSource] absoluteURLStringOfCompletedString:string];
    
    // Open URL
    [_browserController openURLString:urlString];
}

- (void)backToNormalModeAction:(id)sender
{
    // Back to normal mode
    [_browserController backToNormalModeAction:sender];
}

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

- (void)_startUppaerAnimation:(BOOL)appearing
{
    // Show menu bar
    if (appearing) {
        SetSystemUIMode(kUIModeContentHidden, 0);
    }
    
    // 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 - 22.0f;
    
    startFrame = [window frame];
    startFrame.origin.x = endFrame.origin.x;
    startFrame.origin.y = screenFrame.size.height + startFrame.size.height - 22.0f;
    
    if (!appearing) {
        NSRect  rect;
        rect = startFrame;
        startFrame = endFrame;
        endFrame = rect;
    }
    
    [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)_showOrHideControlWithPoint:(NSPoint)point
{
    // Get window
    NSWindow*   window;
    window = [self window];
    
    // Calc bounds for control window
    NSRect  screenFrame;
    NSRect  upperBounds, upperControlBounds;
    screenFrame = [[[_browserController fullScreenWindow] screen] frame];
    upperBounds.origin.x = screenFrame.origin.x;
    upperBounds.origin.y = screenFrame.origin.y + screenFrame.size.height;
    upperBounds.size.width = screenFrame.size.width;
    upperBounds.size.height = 1;
    upperControlBounds.origin.x = screenFrame.origin.x;
    upperControlBounds.origin.y = screenFrame.origin.y + screenFrame.size.height - _SRFullScreenControlHeight;
    upperControlBounds.size.width = screenFrame.size.width;
    upperControlBounds.size.height = _SRFullScreenControlHeight + 1;
    
    // Show control
    if (NSPointInRect(point, upperBounds)) {
        if (!_animation && ![window isVisible]) {
            [self _updateControlView];
            [self _startUppaerAnimation:YES];
            return;
        }
    }
    
    // Hide control
    if (!NSPointInRect(point, upperControlBounds)) {
        if (!_animation && [window isVisible]) {
            [self _startUppaerAnimation:NO];
            return;
        }
    }
}

- (void)hmWindow:(NSWindow*)window mouseMoved:(NSEvent*)event
{
    [self _showOrHideControlWithPoint:
            [window convertBaseToScreen:[event locationInWindow]]];
}

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

- (void)animationDidEnd:(NSAnimation*)animation
{
    // Release animation
    [_animation release], _animation = nil;
    
    // For disapperaning
    NSWindow*   window;
    window = [self window];
    if (!NSIntersectsRect([window frame], [[window screen] frame])) {
        // Hide window
        [window orderOut:self];
        
        // Hide menu bar
        SetSystemUIMode(kUIModeAllHidden, 0);
        
        // Show browser window
        [[_browserController fullScreenWindow] makeKeyAndOrderFront:self];
    }
}

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

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

- (void)window:(NSWindow*)window mouseMoved:(NSEvent*)event
{
    [self _showOrHideControlWithPoint:
            [window convertBaseToScreen:[event locationInWindow]]];
}

//--------------------------------------------------------------//
#pragma mark -- WebVew notification --
//--------------------------------------------------------------//

- (void)progressStarted:(NSNotification*)notification
{
    if ([_progressWindow isVisible]) {
        return;
    }
    
    // Get screen frame
    NSRect  screenFrame;
    screenFrame = [[[_browserController window] screen] frame];
    
    // Show progress window
    NSRect  frame;
    frame.size = [_progressWindow frame].size;
    frame.origin.x = floor((screenFrame.size.width - frame.size.width) / 2.0f);
    frame.origin.y = 100.0f;
    [_progressWindow setFrame:frame display:NO];
    [_progressWindow orderFront:self];
    
    // Start animation
    [_progressIndicator startAnimation:self];
}

- (void)progressFinished:(NSNotification*)notification
{
    if (![_progressWindow isVisible]) {
        return;
    }
    
    // Hide progress window
    [_progressWindow orderOut:self];
    
    // Stop animation
    [_progressIndicator stopAnimation:self];
}

//--------------------------------------------------------------//
#pragma mark -- NSControl delegate --
//--------------------------------------------------------------//

- (void)controlTextDidChange:(NSNotification*)notification
{
    // Get text
    NSString*   string;
    string = [_urlComboBox stringValue];
    
    // Complete text
    NSString*   completedString;
    completedString = [_urlDataSource comboBox:nil completedString:string];
    
    // Swap text
    if (completedString && ![string isEqualToString:completedString]) {
    }
}

//--------------------------------------------------------------//
#pragma mark -- SRPageController notification --
//--------------------------------------------------------------//

- (void)pageDidCommitLoad:(NSNotification*)notification
{
    [self _updateControlView];
}

- (void)pageTitleReceived:(NSNotification*)notification
{
    [self _updateControlView];
}

@end
