/*
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)_updateBookmarkPopUp
{
    // Remove old items
    [_bookmarkBarPopUp removeAllItems];
    
    NSWorkspace*    workspace;
    NSMenuItem*     menuItem;
    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) {
            // Get bundle
            NSString*   browserId;
            NSBundle*   bundle;
            browserId = [_allBrowserIds objectAtIndex:i];
            bundle = [NSBundle bundleWithIdentifier:browserId];
            
            // Add pop up item
            NSString*   title;
            title = [[bundle localizedInfoDictionary] objectForKey:@"CFBundleName"];
            if (!title) {
                title = browser;
            }
            [_bookmarkBarPopUp addItemWithTitle:title];
            menuItem = [_bookmarkBarPopUp lastItem];
            [menuItem setRepresentedObject:browser];
            
            // Set icon
            NSString*   browserPath;
            NSImage*    icon = nil;
            browserPath = [workspace absolutePathForAppBundleWithIdentifier:browserId];
            if (browserPath) {
                icon = [workspace iconForFile:browserPath];
                if (icon) {
                    [icon setSize:NSMakeSize(16, 16)];
                    [menuItem setImage:icon];
                }
            }
        }
    }
    
    // Select pop up item
    NSString*   browser;
    int         index;
    browser = [[NSUserDefaults standardUserDefaults] objectForKey:SRBookmarkBarType];
    if (!browser || ![browser isKindOfClass:[NSString class]]) {
        browser = SRBrowserShiira;
    }
    index = [[_bookmarkBarPopUp menu] indexOfItemWithRepresentedObject:browser];
    if (index == NSNotFound) {
        index = 0;
    }
    [_bookmarkBarPopUp selectItemAtIndex:index];
}

- (void)_updateBookmarkMenuTable
{
    // Get usage flags
    NSDictionary*   usageFlags;
    usageFlags = [[NSUserDefaults standardUserDefaults] 
            objectForKey:SRBookmarkMenuUsageFlags];
    if (![usageFlags isKindOfClass:[NSDictionary class]]) {
        usageFlags = nil;
    }
    
    // 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) {
            // Get bundle
            NSString*   browserId;
            NSBundle*   bundle;
            browserId = [_allBrowserIds objectAtIndex:i];
            bundle = [NSBundle bundleWithIdentifier:browserId];
            
            // Create browser info
            NSMutableDictionary*    browserInfo;
            browserInfo = [NSMutableDictionary dictionary];
            
            // Set title
            NSString*   title;
            title = [[bundle localizedInfoDictionary] objectForKey:@"CFBundleName"];
            if (!title) {
                title = browser;
            }
            [browserInfo setObject:title forKey:@"title"];
            
            // Set browser
            [browserInfo setObject:browser forKey:@"browser"];
            
            // Get icon
            NSString*   browserPath;
            NSImage*    icon = nil;
            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];
        }
    }
}

- (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:
            SRBrowserShiira, SRBrowserSafari, SRBrowserFirefox, nil] retain];
    _allBrowserIds = [[NSArray arrayWithObjects:
            @"jp.hmdt.shiira", @"com.apple.safari", @"org.mozilla.firefox", nil] retain];
    
    // Initialize instance variables
    _browserInfos = [[NSMutableArray array] retain];
    
    return self;
}

- (void)didLoad
{
    // Update bookmark pop up
    [self _updateBookmarkPopUp];
    
    // 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 bookmark menu table
    [self _updateBookmarkMenuTable];
}

- (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:@"title"];
    }
    
    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
