/*
SRHistoryMenuProvider.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 "SRHistoryMenuProvider.h"
#import "SRMenu.h"

// Consntats
int  SRNumberOfDefaultHistoryMenu = 7;
int  SRNumberOfRecentHistoryItem = 8;

@implementation SRHistoryMenuProvider

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

+ (id)sharedInstance
{
    static SRHistoryMenuProvider*   _sharedInstance = nil;
    if (!_sharedInstance) {
        _sharedInstance = [[SRHistoryMenuProvider alloc] init];
    }
    
    return _sharedInstance;
}

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

- (BOOL)menuHasKeyEquivalent:(NSMenu*)menu 
        forEvent:(NSEvent*)event 
        target:(id*)target 
        action:(SEL*)action
{
    return NO;
}

- (int)_numberOfHistoryItemsWithLimit:(int)limit
{
    int count = 0;
    
    WebHistory*     history;
    NSArray*        lastVisitedDays;
    NSCalendarDate* calendarDate;
    NSEnumerator*   enumerator;
    history = [WebHistory optionalSharedHistory];
    lastVisitedDays = [history orderedLastVisitedDays];
    enumerator = [lastVisitedDays objectEnumerator];
    while (calendarDate = [enumerator nextObject]) {
        // Get history items
        NSArray*    historyItems;
        historyItems = [history orderedItemsLastVisitedOnDay:calendarDate];
        if ([historyItems count] >= limit - count) {
            count = limit;
            break;
        }
        
        count += [historyItems count];
    }
    
    return count;
}

- (NSArray*)_lastHistoryItemsWithLimit:(int)limit
{
    NSMutableArray* items;
    items = [NSMutableArray array];
    
    int count = 0;
    
    WebHistory*     history;
    NSArray*        lastVisitedDays;
    NSCalendarDate* calendarDate;
    NSEnumerator*   enumerator;
    history = [WebHistory optionalSharedHistory];
    lastVisitedDays = [history orderedLastVisitedDays];
    enumerator = [lastVisitedDays objectEnumerator];
    while (calendarDate = [enumerator nextObject]) {
        // Get history items
        NSArray*    historyItems;
        historyItems = [history orderedItemsLastVisitedOnDay:calendarDate];
        if ([historyItems count] >= limit - count) {
            [items addObjectsFromArray:[historyItems subarrayWithRange:NSMakeRange(0, limit - count)]];
            break;
        }
        
        [items addObjectsFromArray:historyItems];
        count += [historyItems count];
    }
    
    return items;
}

- (int)numberOfItemsInMenu:(NSMenu*)menu
{
    if ([menu delegate] != self) {
        return 0;
    }
    
    // Get web history and last visited days
    WebHistory* history;
    NSArray*    lastVisitedDays;
    history = [WebHistory optionalSharedHistory];
    lastVisitedDays = [history orderedLastVisitedDays];
    
    // For history menu
    if (menu == SRHistoryMenu()) {
        return SRNumberOfDefaultHistoryMenu + [lastVisitedDays count];
    }
    
    // For calendar date menu
    // Create calendar date from menu title
    NSCalendarDate* calendarDate;
    calendarDate = [[NSCalendarDate alloc] initWithString:[menu title]];
    [calendarDate autorelease];
    
    // Get web history items
    NSArray*    historyItems;
    historyItems = [history orderedItemsLastVisitedOnDay:calendarDate];
    
    return [historyItems count];
}

- (BOOL)menu:(NSMenu*)menu 
        updateItem:(NSMenuItem*)item 
        atIndex:(int)index 
        shouldCancel:(BOOL)shouldCancel
{
    if ([menu delegate] != self) {
        return NO;
    }
    
    // Get web history and last visited days
    WebHistory* history;
    NSArray*    lastVisitedDays;
    history = [WebHistory optionalSharedHistory];
    lastVisitedDays = [history orderedLastVisitedDays];
    
    // For history menu
    if (menu == SRHistoryMenu()) {
        if (index < SRNumberOfDefaultHistoryMenu) {
            return YES;
        }
        
        // Get calendar date
        if ([lastVisitedDays count] < index - SRNumberOfDefaultHistoryMenu) {
            return YES;
        }
        NSCalendarDate* calendarDate;
        calendarDate = [lastVisitedDays objectAtIndex:index - SRNumberOfDefaultHistoryMenu];
        
        // Update item
        [item setTitle:[calendarDate 
                descriptionWithCalendarFormat:NSLocalizedString(@"%a, %B %e", nil) 
                locale:[[NSUserDefaults standardUserDefaults] dictionaryRepresentation]]];
        [item setTag:SRHistoryItemTag];
        
        // Create sub menu
        if (![item submenu]) {
            NSMenu* submenu;
            submenu = [[NSMenu alloc] initWithTitle:[calendarDate description]];
            [submenu setDelegate:self];
            
            [item setSubmenu:submenu];
        }
        else {
            NSMenu* submenu;
            submenu = [item submenu];
            [submenu setTitle:[calendarDate description]];
            [submenu update];
        }
        
        return YES;
    }
    // For calendar date menu
    else {
        NSUserDefaults* defaults;
        defaults = [NSUserDefaults standardUserDefaults];
        
        // Create calendar date from menu title
        NSCalendarDate* calendarDate;
        calendarDate = [[NSCalendarDate alloc] initWithString:[menu title]];
        [calendarDate autorelease];
        
        // Get web history item
        NSArray*        historyItems;
        WebHistoryItem* historyItem;
        historyItems = [history orderedItemsLastVisitedOnDay:calendarDate];
        if ([historyItems count] < index) {
            return YES;
        }
        historyItem = [historyItems objectAtIndex:index];
        
        // Updaate item
        NSString*   title;
        NSImage*    icon;
        title = [historyItem title];
        if (!title || [title length] == 0) {
            title = [historyItem URLString];
        }
        if (!title || [title length] == 0) {
            title = [NSString stringWithFormat:@"(%@)", NSLocalizedString(@"Untitled", nil)];
        }
        
        [item setTitle:HMTruncateString(title, 64, NSLineBreakByTruncatingMiddle)];
        [item setAction:@selector(openHistoryItemAction:)];
        icon = [historyItem icon];
        if (icon) {
            [item setImage:icon];
        }
        [item setRepresentedObject:historyItem];
        
        return YES;
    }
    
    return YES;
}

@end
