/*
SRBookmarkPref.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 "SRBookmarkPref.h"
#import "SRPrefDefaultKeys.h"

#import "SRConstants.h"
#import "SRAppControllerProxy.h"

static NSArray* _allBrowsers = nil;
static NSArray* _allBrowserIds = nil;

@implementation SRBookmarkPref

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

- (void)_updateBrowsers
{
    // Get usage flags
    NSDictionary*   usageFlags;
    usageFlags = [[NSUserDefaults standardUserDefaults] 
            objectForKey:SRBookmarkMenuUsageFlags];
    
    // Remove old browsers
    [_browserInfos removeAllObjects];
    
    NSWorkspace*    workspace;
    workspace = [NSWorkspace sharedWorkspace];
    
    // Check browsers
    int i;
    for (i = 0; i < [_allBrowsers count]; i++) {
        // Get browser
        NSString*   browser;
        browser = [_allBrowsers objectAtIndex:i];
        
        // Get root bookmark
        id  bookmark;
        bookmark = [_appController rootBookmarkOfBrowser:browser];
        if (bookmark) {
            // Create browser info
            NSMutableDictionary*    browserInfo;
            browserInfo = [NSMutableDictionary dictionary];
            
            // Set browser
            [browserInfo setObject:browser forKey:@"browser"];
            
            // Get icon
            NSString*   browserId;
            NSString*   browserPath;
            NSImage*    icon = nil;
            browserId = [_allBrowserIds objectAtIndex:i];
            browserPath = [workspace absolutePathForAppBundleWithIdentifier:browserId];
            if (browserPath) {
                icon = [workspace iconForFile:browserPath];
                if (icon) {
                    [icon setSize:NSMakeSize(16, 16)];
                    [browserInfo setObject:icon forKey:@"icon"];
                }
            }
            
            // Get flag
            NSNumber*   flag;
            flag = [usageFlags objectForKey:browser];
            if (!flag) {
                flag = [NSNumber numberWithBool:YES];
            }
            [browserInfo setObject:flag forKey:@"on"];
            
            // Add browser info
            [_browserInfos addObject:browserInfo];
            
            // Add pop up item
            NSMenuItem* item;
            [_bookmarkBarPopUp addItemWithTitle:browser];
            item = [_bookmarkBarPopUp lastItem];
            if (icon) {
                [item setImage:icon];
            }
        }
    }
}

- (void)_saveUsageFlags
{
    NSMutableDictionary* usageFlags;
    usageFlags = [NSMutableDictionary dictionary];
    
    NSEnumerator*   enumerator;
    NSDictionary*   browserInfo;
    enumerator = [_browserInfos objectEnumerator];
    while (browserInfo = [enumerator nextObject]) {
        [usageFlags setObject:[browserInfo objectForKey:@"on"] 
                forKey:[browserInfo objectForKey:@"browser"]];
    }
    
    // Store in defaults
    [[NSUserDefaults standardUserDefaults] 
            setObject:usageFlags forKey:SRBookmarkMenuUsageFlags];
}

- (id)initWithBundle:(NSBundle*)bundle
{
    self = [super initWithBundle:bundle];
    if (!self) {
        return nil;
    }
    
    // Initialize static variables
    _allBrowsers = [[NSArray arrayWithObjects:
            SRBrowserSafari, SRBrowserFirefox, nil] retain];
    _allBrowserIds = [[NSArray arrayWithObjects:
            @"com.apple.safari", @"org.mozilla.firefox", nil] retain];
    
    // Initialize instance variables
    _browserInfos = [[NSMutableArray array] retain];
    
    return self;
}

- (void)didLoad
{
    // Set image text cell
    NSTableColumn*      column;
    NSCell*             oldCell;
    id                  cell;
    column = [_tableView tableColumnWithIdentifier:@"browser"];
    oldCell = [column dataCell];
    cell = [[NSClassFromString(@"HMImageTextFieldCell") alloc] init];
    if (cell) {
        [cell setFont:[oldCell font]];
        [column setDataCell:cell];
        [cell release];
    }
    
    // Update first item of bookmark bar pop up
    NSMenuItem* menuItem;
    NSImage*    icon;
    menuItem = [_bookmarkBarPopUp itemAtIndex:0];
    icon = [[NSImage alloc] initWithContentsOfFile:
            [[NSBundle mainBundle] pathForResource:@"Shiira" ofType:@"icns"]];
    [icon setSize:NSMakeSize(16, 16)];
    [menuItem setImage:icon];
    [icon release];
    
    // Update browsers
    [self _updateBrowsers];
}

- (void)dealloc
{
    [_browserInfos release], _browserInfos = nil;
    
    [super dealloc];
}

//--------------------------------------------------------------//
#pragma mark -- NSTableView data source --
//--------------------------------------------------------------//

- (int)numberOfRowsInTableView:(NSTableView*)tableView
{
    return [_browserInfos count];
}

- (id)tableView:(NSTableView*)tableView 
        objectValueForTableColumn:(NSTableColumn*)tableColumn 
        row:(int)row
{
    // Get identifier
    id  identifier;
    identifier = [tableColumn identifier];
    
    // For On
    if ([identifier isEqualToString:@"on"]) {
        return [[_browserInfos objectAtIndex:row] objectForKey:@"on"];
    }
    
    // For browser
    if ([identifier isEqualToString:@"browser"]) {
        return [[_browserInfos objectAtIndex:row] objectForKey:@"browser"];
    }
    
    return nil;
}

- (void)tableView:(NSTableView*)tableView 
        setObjectValue:(id)object 
        forTableColumn:(NSTableColumn*)tableColumn 
        row:(int)row
{
    // Get identifier
    id  identifier;
    identifier = [tableColumn identifier];
    
    // For On
    if ([identifier isEqualToString:@"on"]) {
        // Set usage flag
        NSMutableDictionary*    browserInfo;
        browserInfo = [_browserInfos objectAtIndex:row];
        [browserInfo setObject:object forKey:@"on"];
        
        // Store in defaults
        [self _saveUsageFlags];
    }
}

//--------------------------------------------------------------//
#pragma mark -- NSTableView delegae --
//--------------------------------------------------------------//

- (void)tableView:(NSTableView*)tableView 
        willDisplayCell:(id)cell 
        forTableColumn:(NSTableColumn*)tableColumn 
        row:(int)row
{
    // Get identifier
    id  identifier;
    identifier = [tableColumn identifier];
    
    // For browser
    if ([identifier isEqualToString:@"browser"]) {
        // Set icon
        NSImage*    icon;
        icon = [[_browserInfos objectAtIndex:row] objectForKey:@"icon"];
        if (icon) {
            [cell setImage:icon];
        }
        else {
            [cell setImage:nil];
        }
    }
}

@end
