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

#import "SRBookmarkButton.h"
#import "SRBookmarkButtonCell.h"
#import "SRBookmarkMenuProvider.h"

#import "SRPrefDefaultKeys.h"

#import "SRMenu.h"
#import "SRBookmarkContextMenu.h"

@implementation SRBookmarkButton

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

+ (Class)cellClass
{
    return [SRBookmarkButtonCell class];
}

- (id)initWithFrame:(NSRect)frame
{
    self = [super initWithFrame:frame];
    if (!self) {
        return nil;
    }
    
    // Initialize instance variables
    _hovered = NO;
    
    // Configure itself
    [self setMenuFont:[NSFont systemFontOfSize:[NSFont systemFontSize]]];
    
    return self;
}

- (void)viewDidMoveToWindow
{
    // Shows border only while mouse inside
    [self setShowsBorderOnlyWhileMouseInside:YES];
}

- (BOOL)acceptsFirstResponder
{
    return NO;
}

//--------------------------------------------------------------//
#pragma mark -- Drawing --
//--------------------------------------------------------------//

- (BOOL)isHovered
{
    return _hovered;
}

- (void)setHovered:(BOOL)hovered
{
    _hovered = hovered;
}

//--------------------------------------------------------------//
#pragma mark -- Bookmark --
//--------------------------------------------------------------//

- (void)setBookmark:(SRBookmark*)bookmark
{
    [[self cell] setBookmark:bookmark];
    
    // For folder
    if ([[bookmark isFolder] boolValue] && ![[bookmark isAutoTab] boolValue]) {
        // Set menu
        SRMenu* menu;
        menu = (SRMenu*)[self menu];
        if (!menu) {
            menu = [[SRMenu alloc] initWithTitle:@"bookmark"];
        }
        [menu autorelease];
        [menu setDelegate:self];
        [menu setRepresentedObject:bookmark];
        
        [self setMenu:menu];
    }
}

- (SRBookmark*)bookmark
{
    return [[self cell] bookmark];
}

//--------------------------------------------------------------//
#pragma mark -- Mouse handling --
//--------------------------------------------------------------//

- (void)mouseDown:(NSEvent*)event
{
    _mouseDownEvent = event;
    [super mouseDown:event];
    _mouseDownEvent = nil;
}

- (void)mouseUp:(NSEvent*)event
{
    [super mouseUp:event];
}

- (NSEvent*)mouseDownEvent
{
    return _mouseDownEvent;
}

- (NSMenu*)menuForEvent:(NSEvent*)event
{
    NSUserDefaults* defaults;
    defaults = [NSUserDefaults standardUserDefaults];
    
    // Make itself highlighted
    [[self cell] setHighlighted:YES];
    
    // Get bookmark
    SRBookmark* bookmark;
    bookmark = [self bookmark];
    
    // Check tab availability
    BOOL    selectNewTabs;
    selectNewTabs = [defaults boolForKey:SRTabSelectNewTabs];
    
    // Get bookmark context menu
    NSMenu*     menu;
    NSMenu*     bookmarkMenu;
    NSMenuItem* menuItem;
    NSMenuItem* altMenuItem;
    menu = [[NSMenu alloc] initWithTitle:@""];
    [menu autorelease];
    bookmarkMenu = [SRBookmarkContextMenu contextMenu];
    
    // Create tag array
    NSMutableArray* tags;
    tags = [NSMutableArray array];
    
    // Case of HTML bookmark
    if (![[bookmark isFolder] boolValue]) {
        // 'Open Bookmark'
        menuItem = HMCopyMenuItemWithTag(bookmarkMenu, SROpenBookmarkTag, nil);
        [menuItem setRepresentedObject:bookmark];
        [menu addItem:menuItem];
        
        // 'Open Bookmark in New Tab' and 'Open Bookmark in Background Tab'
        if (selectNewTabs) {
            menuItem = HMCopyMenuItemWithTag(bookmarkMenu, SROpenBookmarkInNewTabTag, nil);
            altMenuItem = HMCopyMenuItemWithTag(bookmarkMenu, SROpenBookmarkInNewBackgroundTabTag, nil);
        }
        else{
            menuItem = HMCopyMenuItemWithTag(bookmarkMenu, SROpenBookmarkInNewBackgroundTabTag, nil);
            altMenuItem = HMCopyMenuItemWithTag(bookmarkMenu, SROpenBookmarkInNewTabTag, nil);
        }
        [menuItem setRepresentedObject:bookmark];
        [menu addItem:menuItem];
        
        [altMenuItem setRepresentedObject:bookmark];
        [altMenuItem setKeyEquivalentModifierMask:NSShiftKeyMask];
        [altMenuItem setAlternate:YES];
        [menu addItem:altMenuItem];
        
        // 'Open Bookmark in New Window' and 'Open Bookmark in Background Window'
        if (selectNewTabs) {
            menuItem = HMCopyMenuItemWithTag(bookmarkMenu, SROpenBookmarkInNewWindowTag, nil);
            altMenuItem = HMCopyMenuItemWithTag(bookmarkMenu, SROpenBookmarkInNewBackgroundWindowTag, nil);
        }
        else{
            menuItem = HMCopyMenuItemWithTag(bookmarkMenu, SROpenBookmarkInNewBackgroundWindowTag, nil);
            altMenuItem = HMCopyMenuItemWithTag(bookmarkMenu, SROpenBookmarkInNewWindowTag, nil);
        }
        [menuItem setRepresentedObject:bookmark];
        [menu addItem:menuItem];
        
        [altMenuItem setRepresentedObject:bookmark];
        [altMenuItem setKeyEquivalentModifierMask:NSShiftKeyMask];
        [altMenuItem setAlternate:YES];
        [menu addItem:altMenuItem];
        
        // 'Delete Bookmark'
        if ([bookmark isMutable]) {
            menuItem = HMCopyMenuItemWithTag(bookmarkMenu, SRDeleteBookmarkTag, nil);
            [menuItem setRepresentedObject:bookmark];
            [menu addItem:menuItem];
        }
    }
    // Case of bookmark folder
    else {
        // 'Open Bookmark in Tabs'
        menuItem = HMCopyMenuItemWithTag(bookmarkMenu, SROpenBookmarkInTabsTag, nil);
        [menuItem setRepresentedObject:bookmark];
        [menu addItem:menuItem];
        
        // 'Delete Bookmark'
        if ([bookmark isMutable]) {
            menuItem = HMCopyMenuItemWithTag(bookmarkMenu, SRDeleteBookmarkTag, nil);
            [menuItem setRepresentedObject:bookmark];
            [menu addItem:menuItem];
        }
    }
    
    // Register notification
    NSNotificationCenter*   center;
    center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(_menuDidEndTracking:) 
            name:NSMenuDidEndTrackingNotification object:menu];
    
    return menu;
}

- (void)_menuDidEndTracking:(NSNotification*)notification
{
    NSNotificationCenter*   center;
    center = [NSNotificationCenter defaultCenter];
    
    // Remove notification
    [center removeObserver:self name:NSMenuDidEndTrackingNotification 
            object:[notification object]];
    
    // Clear highlight
    [[self cell] setHighlighted:NO];
}

//--------------------------------------------------------------//
#pragma mark -- NSMenu delegate --
//--------------------------------------------------------------//

- (void)menuNeedsUpdate:(NSMenu*)menu
{
    // Check delegate
    if ([menu delegate] != self) {
        return;
    }
    
    // Get bookmark as represented object
    SRBookmark* bookmark;
    bookmark = [(SRMenu*)menu representedObject];
    if (!bookmark || ![[bookmark isFolder] boolValue]) {
        return;
    }
    
    // Remove old items
    int i;
    for (i = [menu numberOfItems] - 1; i >= 0; i--) {
        [menu removeItemAtIndex:i];
    }
    
    // Get children bookmark
    NSMutableArray* children;
    children = [NSMutableArray arrayWithArray:[[bookmark valueForKey:@"children"] allObjects]];
    if ([children count] == 0) {
        [menu addItemWithTitle:NSLocalizedString(@"No item", nil) action:NULL keyEquivalent:@""];
        return;
    }
    
    // Append children
    [[SRBookmarkMenuProvider sharedInstance] 
            appendBookmarks:HMSortWithKey(children, @"index", YES) intoMenu:menu withShortcut:NO];
}

@end
