/*
SRHistoryShelf.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 "SRWebHistoryProxy.h"
#import "SRAppControllerProxy.h"
#import "SRBrowserControllerProxy.h"
#import "SRConstants.h"

#import "SRHistoryShelf.h"

#import "SRHistoryContextMenu.h"

#import "SRPrefDefaultKeys.h"

@implementation SRHistoryShelf

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

- (void)didLoad
{
    // Create buttons
    _contextButton = [[NSClassFromString(@"HMMenuButton") alloc] initWithFrame:NSMakeRect(0, 0, 31, 19)];
    [_contextButton setButtonType:NSMomentaryChangeButton];
    [_contextButton setBezelStyle:NSRegularSquareBezelStyle];
    [_contextButton setBordered:NO];
    [_contextButton setImage:[NSImage imageNamed:@"shelfContext"]];
    [_contextButton setSelectedImage:[NSImage imageNamed:@"shelfPressedBackgroundL"]];
    [_contextButton setFont:[NSFont systemFontOfSize:[NSFont systemFontSize]]];
    [_contextButton setDelegate:self];
    [_contextButton setTarget:self];
    
    // Configure outline
    [_outlineView setDoubleAction:@selector(openHistoryAction:)];
    [_outlineView setAutoresizesOutlineColumn:NO];
    
    // Set image text cell
    NSTableColumn*      column;
    NSCell*             oldCell;
    id                  cell;
    
    cell = [[NSClassFromString(@"HMImageTextFieldCell") alloc] init];
    column = [_outlineView tableColumnWithIdentifier:@"title"];
    oldCell = [column dataCell];
    [cell setFont:[oldCell font]];
    [column setDataCell:cell];
    [cell release];
    
    // Configure split view
    [_splitView setSplitType:HMSplitWide];
    
    // Set web history
    [_historyTreeController setContent:[[self webHistory] treeWebHistory]];
    
    // Register notification
    NSNotificationCenter*   center;
    center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(webHistoryUpdated:) 
            name:SRWebHistoryUpdated object:nil];
}

- (void)dealloc
{
    // Remove observer
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    [_contextButton release], _contextButton = nil;
    
    [super dealloc];
}

//--------------------------------------------------------------//
#pragma mark -- Bar buttons --
//--------------------------------------------------------------//

- (NSArray*)rightBarButtons
{
    return [NSArray arrayWithObjects:_contextButton, nil];
}

//--------------------------------------------------------------//
#pragma mark -- History --
//--------------------------------------------------------------//

- (NSArray*)selectedHistoryItems
{
    // Get selected objects
    return [_historyTreeController selectedObjects];
}

- (NSMenu*)_menuForView:(id)view 
        event:(NSEvent*)event
{
    NSUserDefaults* defaults;
    defaults = [NSUserDefaults standardUserDefaults];
    
    // Get modifier key flag
    unsigned int    modifierFlags;
    unsigned int    cmdFlag, optionFlag, shiftFlag;
    modifierFlags = [event modifierFlags];
    cmdFlag = modifierFlags & NSCommandKeyMask;
    optionFlag = modifierFlags & NSAlternateKeyMask;
    shiftFlag = modifierFlags & NSShiftKeyMask;
    
    // Create array for tags
    NSMutableArray* tags;
    tags = [NSMutableArray array];
    
    // Select history item under the cursor
    NSPoint point;
    int     rowUnderPoint;
    point = [view convertPoint:[event locationInWindow] 
            fromView:nil];
    rowUnderPoint = [view rowAtPoint:point];
    if (![[view selectedRowIndexes] containsIndex:rowUnderPoint]) {
        [view selectRowIndexes:[NSIndexSet indexSetWithIndex:rowUnderPoint] 
                byExtendingSelection:NO];
    }
    
    // Get selected rows
    NSIndexSet* indexSet;
    indexSet = [view selectedRowIndexes];
    
    WebHistoryItem* historyItem = nil;
    NSArray*        historyItems = nil;
    
    // No bookmark is selected
    if ([indexSet count] == 0) {
        // No menu
    }
    else {
        // Just one history item is selected
        if ([indexSet count] == 1) {
            // Get history item
            historyItem = [[self selectedHistoryItems] objectAtIndex:0];
        }
        else {
            // Get history items
            historyItems = [self selectedHistoryItems];
        }
        
        // Check tab availability
        BOOL    selectNewTabs;
        selectNewTabs = [defaults boolForKey:SRTabSelectNewTabs];
        
        // Case of one history item
        if (historyItem && [historyItem isKindOfClass:[WebHistoryItem class]]) {
            // Create tag array
            [tags addObject:[NSNumber numberWithInt:SROpenHistoryTag]];
            
            if ((selectNewTabs && !shiftFlag) || 
                (!selectNewTabs && shiftFlag))
            {
                [tags addObject:[NSNumber numberWithInt:SROpenHistoryInNewWindowTag]];
                [tags addObject:[NSNumber numberWithInt:SROpenHistoryInNewTabTag]];
            }
            else {
                [tags addObject:[NSNumber numberWithInt:SROpenHistoryInNewBackgroundWindowTag]];
                [tags addObject:[NSNumber numberWithInt:SROpenHistoryInNewBackgroundTabTag]];
            }
            [tags addObject:[NSNumber numberWithInt:SROpenHistoryInNewWindowTag]];
            
            [tags addObject:[NSNumber numberWithInt:SRDeleteHistoryTag]];
        }
        // Case of one folder
        if (historyItem && [historyItem isKindOfClass:[NSCalendarDate class]]) {
            // Create tag array
            [tags addObject:[NSNumber numberWithInt:SRDeleteHistoryTag]];
        }
        // Case of multiple history items
        if (historyItems) {
            // Check existence of history item
            BOOL            isContainedHistoryItem = NO;
            NSEnumerator*   enumerator;
            WebHistoryItem* tmp;
            enumerator = [historyItems objectEnumerator];
            while (tmp = [enumerator nextObject]) {
                if ([tmp isKindOfClass:[WebHistoryItem class]]) {
                    isContainedHistoryItem = YES;
                    break;
                }
            }
            
            // Create tag array
            if (isContainedHistoryItem) {
                [tags addObject:[NSNumber numberWithInt:SROpenHistoryInTabsTag]];
            }
            [tags addObject:[NSNumber numberWithInt:SRDeleteHistoryTag]];
        }
    }
    
    if ([tags count] > 0) {
        // Copy menu
        NSMenu* menu;
        menu = HMCopyMenuWithTags([SRHistoryContextMenu contextMenu], tags, self);
        
        // Set represented object
        if (historyItem) {
            [[menu itemArray] makeObjectsPerformSelector:@selector(setRepresentedObject:) 
                    withObject:historyItem];
        }
        if (historyItems) {
            [[menu itemArray] makeObjectsPerformSelector:@selector(setRepresentedObject:) 
                    withObject:historyItems];
        }
        
        return menu;
    }
    
    return nil;
}

//--------------------------------------------------------------//
#pragma mark -- Display style --
//--------------------------------------------------------------//

- (void)_updateLowerView
{
    // Get lower view bounds
    NSRect  bounds;
    bounds = [_lowerView bounds];
    
    // Get selected history
    NSArray*    histories;
    histories = [self selectedHistoryItems];
    if ([histories count] == 0) {
        // Clear lower view
        [[_lowerView subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];
        return;
    }
    
    // Get old view
    NSView* oldView = nil;
    if ([[_lowerView subviews] count] > 0) {
        oldView = [[_lowerView subviews] objectAtIndex:0];
    }
    
    // For multiple view
    if ([histories count] > 1) {
        return;
    }
    
#if 1
    id  newView = nil;
    newView = _historyView;
#else
    // Get selected history
    id<SRHistory>   history;
    history = [histories objectAtIndex:0];
    type = [bookmark type];
    
    // For HTML
    id  newView = nil;
    if ([type isEqualToString:SRBookmarkTypeHTML]) {
        newView = _bookmarkView;
    }
    
    // For folder
    if ([type isEqualToString:SRBookmarkTypeFolder] || 
        [type isEqualToString:SRBookmarkTypeBookmarkBar] || 
        [type isEqualToString:SRBookmarkTypeBookmarkMenu])
    {
        newView = _folderView;
    }
    
    // For JavaScript
    if ([type isEqualToString:SRBookmarkTypeJavaScript]) {
        newView = _javaScriptView;
    }
    
    // For smart
    if ([type isEqualToString:SRBookmarkTypeSmart]) {
        newView = _smartView;
    }
#endif
    
    // Swap view
    if (newView != oldView) {
        [oldView removeFromSuperview];
        
        [newView setFrame:bounds];
        [_lowerView addSubview:newView];
    }
}

//--------------------------------------------------------------//
#pragma mark -- Action --
//--------------------------------------------------------------//

- (void)openHistoryAction:(id)sender
{
    // Get selected history items
    NSArray*        historyItems;
    WebHistoryItem* historyItem;
    historyItems = [self selectedHistoryItems];
    if ([historyItems count] == 0) {
        return;
    }
    historyItem = [historyItems objectAtIndex:0];
    
    // Open history
    [[self browserController] openInNewTabHistory:historyItem];
}

- (void)openHistoryInNewWindowAction:(id)sender
{
    // Get selected history items
    NSArray*        historyItems;
    WebHistoryItem* historyItem;
    historyItems = [self selectedHistoryItems];
    if ([historyItems count] == 0) {
        return;
    }
    historyItem = [historyItems objectAtIndex:0];
    
    // Open history
    [[self browserController] openInNewWindowHistory:historyItem];
}

- (void)openHistoryInNewBackgroundWindowAction:(id)sender
{
    // Get selected history items
    NSArray*        historyItems;
    WebHistoryItem* historyItem;
    historyItems = [self selectedHistoryItems];
    if ([historyItems count] == 0) {
        return;
    }
    historyItem = [historyItems objectAtIndex:0];
    
    // Open history
    [[self browserController] openInNewBackgroundWindowHistory:historyItem];
}

- (void)openHistoryInNewTabAction:(id)sender
{
    // Get selected history items
    NSArray*        historyItems;
    WebHistoryItem* historyItem;
    historyItems = [self selectedHistoryItems];
    if ([historyItems count] == 0) {
        return;
    }
    historyItem = [historyItems objectAtIndex:0];
    
    // Open history
    [[self browserController] openInNewTabHistory:historyItem select:YES];
}

- (void)openHistoryInNewBackgroundTabAction:(id)sender
{
    // Get selected history items
    NSArray*        historyItems;
    WebHistoryItem* historyItem;
    historyItems = [self selectedHistoryItems];
    if ([historyItems count] == 0) {
        return;
    }
    historyItem = [historyItems objectAtIndex:0];
    
    // Open history
    [[self browserController] openInNewTabHistory:historyItem select:NO];
}

- (void)openHistoryInTabsAction:(id)sender
{
}

- (void)deleteHistoryAction:(id)sender
{
}

- (void)addHistoryToBookmarkAction:(id)sender
{
}

- (void)bookmarkAllHistoryAction:(id)sender
{
}

//--------------------------------------------------------------//
#pragma mark -- NSOutlineView delegate --
//--------------------------------------------------------------//

- (void)outlineView:(NSOutlineView*)outlineView 
        willDisplayCell:(id)cell 
        forTableColumn:(NSTableColumn*)column 
        item:(id)item
{
    // History outline
    if (outlineView == _outlineView) {
        // Get column identifier
        id  identifier;
        identifier = [column identifier];
        
        // For title column
        if ([identifier isEqualToString:@"title"]) {
            // Set image
            if ([item respondsToSelector:@selector(observedObject)]) {
                id  observedObject;
                observedObject = [item performSelector:@selector(observedObject)];
                if ([observedObject isKindOfClass:[NSDictionary class]]) {
                    [cell setImage:[NSImage imageNamed:@"historyFolder"]];
                }
                else {
                    // Set icon
                    NSString*   URLString;
                    NSImage*    icon;
                    URLString = [observedObject URLString];
                    if ([[WebIconDatabase sharedIconDatabase] iconURLForURL:URLString]) {
                        icon = [[WebIconDatabase sharedIconDatabase] 
                                iconForURL:URLString withSize:NSMakeSize(16, 16)];
                    }
                    else {
                        icon = [NSImage imageNamed:@"historyPage"];
                    }
                    [cell setImage:icon];
                }
            }
            
            return;
        }
    }
}

- (void)outlineViewSelectionDidChange:(NSNotification*)notification
{
    // Update appearance
    [self _updateLowerView];
}

//--------------------------------------------------------------//
#pragma mark -- NSOutlineViewEx delegate --
//--------------------------------------------------------------//

- (NSMenu*)outlineView:(NSOutlineView*)outlineView menuForEvent:(NSEvent*)event
{
    return [self _menuForView:outlineView event:event];
}

//--------------------------------------------------------------//
#pragma mark -- HMMenuButton delegate --
//--------------------------------------------------------------//

- (NSMenu*)menuButton:(HMMenuButton*)menuButton menuForEvent:(NSEvent*)event
{
    return [self _menuForView:_outlineView event:event];
}

//--------------------------------------------------------------//
#pragma mark -- SRWebHistory notification --
//--------------------------------------------------------------//

- (void)webHistoryUpdated:(NSNotification*)notification
{
    // Reset content
    [_historyTreeController setContent:[[self webHistory] treeWebHistory]];
}

@end
