/*
SRURLAutoComplete.m

Author: Makoto Kinoshita

Copyright 2004 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 "SRMainWindowController.h"
#import "SRVisualHistoryStorage.h"
#import "SRVHBackForwardController.h"
#import "SRUtil.h"

#import "SRSelectableImageCell.h"

@implementation SRVHBackForwardController

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

+ (SRVHBackForwardController*)sharedInstance
{
    static SRVHBackForwardController*   _sharedInstance = nil;
    if (!_sharedInstance) {
        // Load window
        _sharedInstance = [[SRVHBackForwardController alloc] 
                initWithWindowNibName:@"VHBackForward"];
        if (!_sharedInstance) {
            // Fatal
            SR_FATAL(@"Could not load VHBackForward.nib");
        }
        // Load nib
        [_sharedInstance window];
    }
    
    return _sharedInstance;
}

- (id)initWithWindowNibName:(NSString*)nibName
{
    self = [super initWithWindowNibName:nibName];
    if (!self) {
        return nil;
    }
    
    // Initialize member variables
    _isSelectedByController = NO;
    _isGoingByController = NO;
    
    // Register notifications
    NSNotificationCenter*   center;
    center = [NSNotificationCenter defaultCenter];
    [center addObserver:self 
            selector:@selector(visualHistoryProgressStarted:) 
            name:SRVisulaHistoryProgressStartedNotification 
            object:nil];
    [center addObserver:self 
            selector:@selector(visualHistoryProgressEstimateChanged:) 
            name:SRVisulaHistoryProgressEstimateChangedNotification 
            object:nil];
    [center addObserver:self 
            selector:@selector(visualHistoryProgressFinished:) 
            name:SRVisulaHistoryProgressFinishedNotification 
            object:nil];
    [center addObserver:self 
            selector:@selector(mainWindowGoToHistoryItem:) 
            name:SRMainWindowGoToHistotyItem 
            object:nil];
    [center addObserver:self 
            selector:@selector(mainWindowSelectedWebViewChanged:) 
            name:SRMainWindowSelectedWebViewChanged 
            object:nil];
    [center addObserver:self 
            selector:@selector(mainWindowDidChangeLocationWithinPage:) 
            name:SRMainWindowDidChangeLocationWithinPage 
            object:nil];
    [center addObserver:self 
            selector:@selector(mainWindowDidBecomeMain:) 
            name:SRMainWindowDidBecomeMain 
            object:nil];
    [center addObserver:self 
            selector:@selector(mainWindowDidResignMain:) 
            name:SRMainWindowDidResignMain 
            object:nil];
    
    return self;
}

- (void)awakeFromNib
{
    // Configure window
    NSWindow*   window;
    window = [self window];
    
    if (![window frameAutosaveName]) {
        [window setFrameAutosaveName:@"SRVHBackForwardWindowFrame"];
    }
    
    NSSize  minSize, maxSize;
    minSize = [window minSize];
    maxSize = [window maxSize];
    if (minSize.width != maxSize.width) {
        maxSize.width = minSize.width;
        [window setMaxSize:maxSize];
    }
    
    // Configure matrix
    NSImageCell*            oldCell;
    SRSelectableImageCell*  prototype;
    oldCell = [_matrix cellAtRow:0 column:0];
    prototype = [[SRSelectableImageCell alloc] init];
    [prototype setImageAlignment:[oldCell imageAlignment]];
    [prototype setImageScaling:[oldCell imageScaling]];
    [prototype setImageFrameStyle:[oldCell imageFrameStyle]];
    [prototype setTarget:self];
    [prototype setAction:@selector(visualHistoryItemSelected:)];
    [_matrix setPrototype:prototype];
    
    // Remove all cells of matrix
    int num;
    num = [_matrix numberOfRows];
    while (num--) {
        [_matrix removeRow:0];
    }
    
    [_matrix sizeToCells];
    [_matrix setNeedsDisplay:YES];
}

//--------------------------------------------------------------//
#pragma mark -- Visual history management --
//--------------------------------------------------------------//

- (WebView*)webView
{
    // Get front main window
    NSWindow*   frontWindow;
    frontWindow = SRGetFrontMainWindow();
    if (!frontWindow) {
        return nil;
    }
    
    // Get web view
    return [(SRMainWindowController*)[frontWindow windowController] selectedWebView];
}

- (void)update
{
    // Get web view and back forward list
    WebView*            webView;
    WebBackForwardList* list;
    webView = [self webView];
    list = [webView backForwardList];
    if (!list) {
        return;
    }
    
    // Count itmes
    int backCount, forwardCount, count;
    backCount = [list backListCount];
    forwardCount = [list forwardListCount];
    count = backCount + forwardCount + 1;
    
    // Renew matrix
    _isSelectedByController = YES;
    [_matrix renewRows:count columns:1];
    
    // Get storage
    SRVisualHistoryStorage* storage;
    storage = [SRVisualHistoryStorage sharedInstance];
    
    // Add items
    int i;
    for (i = 0; i < count; i++) {
        // Get history item
        WebHistoryItem* historyItem;
        historyItem = [list itemAtIndex:(count - 1 - i) - backCount];
        if (!historyItem) {
            continue;
        }
        
        // Get image
        NSImage*    image;
        image = [storage imageForHistoryItem:historyItem];
        if (!image) {
            continue;
        }
        
        // Add image
        NSImageCell*    cell;
        cell = [_matrix cellAtRow:i column:0];
        [cell setImage:image];
    }
    
    // Select current item
    [_matrix selectCellAtRow:forwardCount column:0];
    _isSelectedByController = NO;
    
    // Update matrix
    [_matrix sizeToCells];
    [_matrix setNeedsDisplay:YES];
}

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

- (void)visualHistoryItemSelected:(id)sender
{
    // When selected by this controller
    if (_isSelectedByController || _isGoingByController) {
        return;
    }
    
    // Get front main window
    NSWindow*   frontWindow;
    frontWindow = SRGetFrontMainWindow();
    if (!frontWindow) {
        return;
    }
    
    // Get web view and back forward list
    WebView*            webView;
    WebBackForwardList* list;
    webView = [(SRMainWindowController*)[frontWindow windowController] selectedWebView];
    list = [webView backForwardList];
    if (!list) {
        return;
    }
    
    // Count itmes
    int backCount, forwardCount, count;
    backCount = [list backListCount];
    forwardCount = [list forwardListCount];
    count = backCount + forwardCount + 1;
    
    // Get selected row
    int row;
    row = [_matrix selectedRow];
    if (row == forwardCount) {
        return;
    }
    
    // Get web history item
    WebHistoryItem* historyItem;
    historyItem = [list itemAtIndex:(count - 1 - row) - backCount];
    if (!historyItem) {
        return;
    }
    
    // Go to this item
    _isGoingByController = YES;
    [webView goToBackForwardItem:historyItem];
    _isGoingByController = NO;
    
    // Make front window main
    [frontWindow makeKeyAndOrderFront:self];
}

//--------------------------------------------------------------//
#pragma mark -- SRVisualHistoryStorage notification --
//--------------------------------------------------------------//

- (void)visualHistoryProgressStarted:(NSNotification*)notification
{
    [self update];
}

- (void)visualHistoryProgressEstimateChanged:(NSNotification*)notification
{
}

- (void)visualHistoryProgressFinished:(NSNotification*)notification
{
    [self update];
}

//--------------------------------------------------------------//
#pragma mark -- SRMainWindowController notification --
//--------------------------------------------------------------//

- (void)mainWindowGoToHistoryItem:(NSNotification*)notification
{
    [self update];
}

- (void)mainWindowSelectedWebViewChanged:(NSNotification*)notification
{
    [self update];
}

- (void)mainWindowDidChangeLocationWithinPage:(NSNotification*)notification
{
    [self update];
}

- (void)mainWindowDidBecomeMain:(NSNotification*)notification
{
    [self performSelector:@selector(update) withObject:nil afterDelay:0.0];
}

- (void)mainWindowDidResignMain:(NSNotification*)notification
{
    [self performSelector:@selector(update) withObject:nil afterDelay:0.0];
}

@end
