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

#import "SRGeneralPref.h"
#import "SRPrefDefaultKeys.h"

#import "SRBrowserMenuProvider.h"
#import "SRBookmarkMenuProvider.h"

// Utility
NSWindow* SRGetFrontBrowserWindow();

@interface SRGeneralPref (private)
// Bookmark
- (void)_udpateBookmarkTextField;
@end

@implementation SRGeneralPref

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

- (void)awakeFromNib
{
    // Configure outline
    NSTableColumn*      column;
    NSCell*             oldCell;
    id                  cell;
    column = [_bookmarkOutline tableColumnWithIdentifier:@"title"];
    oldCell = [column dataCell];
    cell = [[NSClassFromString(@"HMImageTextFieldCell") alloc] init];
    if (cell) {
        [cell setFont:[oldCell font]];
        [column setDataCell:cell];
        [cell release];
    }
    
    // Configure text field
    oldCell = [_bookmarkTextField cell];
    cell = [[NSClassFromString(@"HMImageTextFieldCell") alloc] init];
    if (cell) {
        [cell setFont:[oldCell font]];
        [_bookmarkTextField setCell:cell];
        [cell release];
    }
}

- (void)didLoad
{
    // Update browser pop up menu
    NSMenu*         menu;
    NSArray*        menuItems;
    NSEnumerator*   enumerator;
    NSMenuItem*     menuItem;
    menu = [_browserPopUp menu];
    menuItems = SRBrowserMenuItems(YES);
    
    [_browserPopUp removeAllItems];
    enumerator = [menuItems objectEnumerator];
    while (menuItem = [enumerator nextObject]) {
        [menuItem setTarget:self];
        [menu addItem:menuItem];
    }
    
    // Select current default browser
    NSString*   browserId;
    browserId = (NSString*)LSCopyDefaultHandlerForURLScheme(CFSTR("http"));
    if (browserId) {
        int index;
        index = [_browserPopUp indexOfItemWithRepresentedObject:browserId];
        if (index != NSNotFound) {
            [_browserPopUp selectItemAtIndex:index];
        }
        
        [browserId release];
    }
    
    // Update bookmark text field
    [self _udpateBookmarkTextField];
}

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

- (void)_udpateBookmarkTextField
{
    // Get stored bookmark
    id          bookmark = nil;
    NSString*   bookmarkId;
    bookmarkId = [[NSUserDefaults standardUserDefaults] stringForKey:SRGeneralBookmark];
    if (bookmarkId) {
        NSManagedObjectID*  managedObjectId;
        managedObjectId = [[[self appController] persistentStoreCoordinator] 
                managedObjectIDForURIRepresentation:[NSURL URLWithString:bookmarkId]];
        if (managedObjectId) {
            bookmark = [[[self appController] managedObjectContext] objectRegisteredForID:managedObjectId];
        }
    }
    if (!bookmark) {
        NSDictionary*       attr;
        NSAttributedString* attrStr;
        attr = [NSDictionary dictionaryWithObjectsAndKeys:
                [NSColor grayColor], NSForegroundColorAttributeName, 
                nil];
        attrStr = [[NSAttributedString alloc] 
                initWithString:NSLocalizedString(@"No bookmark is specified", nil) 
                attributes:attr];
        [_bookmarkTextField setAttributedStringValue:attrStr];
        [[_bookmarkTextField cell] setImage:nil];
        [_bookmarkTextField setEnabled:NO];
        return;
    }
    
    // Set bookmark
    [_bookmarkTextField setStringValue:[bookmark valueForKey:@"title"]];
    [[_bookmarkTextField cell] setImage:[bookmark valueForKey:@"icon"]];
    [_bookmarkTextField setEnabled:YES];
}

//--------------------------------------------------------------//
#pragma mark -- Persistent stack --
//--------------------------------------------------------------//

- (NSManagedObjectContext*)managedObjectContext
{
    return [[self appController] managedObjectContext];
}

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

- (void)setHomePageAsCurrentAction:(id)sender
{
    // Get front window
    NSWindow*   frontWindow;
    frontWindow = SRGetFrontBrowserWindow();
    if (!frontWindow) {
        return;
    }
    
    // Get URL string
    WebView*    webView;
    NSString*   URLString;
    webView = [[[frontWindow windowController] performSelector:@selector(selectedPageController)] webView];
    URLString = [[[[[webView mainFrame] dataSource] request] URL] absoluteString];
    if (!URLString) {
        return;
    }
    
    // Set to current page
    NSUserDefaults* defaults;
    defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:URLString forKey:SRGeneralHomePage];
}

- (void)openURLWithAction:(id)sender
{
    // Get selected browser ID
    NSString*   browserId;
    browserId = [[_browserPopUp selectedItem] representedObject];
    if (!browserId) {
        return;
    }
    
    // Set default browser
    OSStatus    status;
    status = LSSetDefaultHandlerForURLScheme(CFSTR("http"), (CFStringRef)browserId);
}

- (void)openBookmarkPanelAction:(id)sender
{
    // Bind managed object context
    [_bookmarkTreeController bind:@"managedObjectContext" 
            toObject:self withKeyPath:@"managedObjectContext" options:nil];
    
    // Prepare content
    [_bookmarkTreeController prepareContent];
    
    // Open bookmark panel
    [NSApp beginSheet:_bookmarkPanel 
            modalForWindow:[_mainView window] 
            modalDelegate:self 
            didEndSelector:@selector(bookmarkSheetDidEnd:returnCode:contextInfo:) 
            contextInfo:nil];
}

- (void)bookmarkSheetDidEnd:(NSWindow*)sheet 
        returnCode:(int)returnCode 
        contextInfo:(void*)contextInfo
{
    // Close sheet
    [_bookmarkPanel orderOut:self];
    
    // Check return code
    if (returnCode != 0) {
        return;
    }
    
    // Get selected bookmark
    NSArray*    selectedObjects;
    id          bookmark = nil;
    selectedObjects = [_bookmarkTreeController selectedObjects];
    if ([selectedObjects count] > 0) {
        bookmark = [selectedObjects objectAtIndex:0];
    }
    if (!bookmark) {
        return;
    }
    
    // Store bookmark ID
    NSString*   bookmarkId;
    bookmarkId = [[[bookmark objectID] URIRepresentation] absoluteString];
    if (bookmarkId) {
        [[NSUserDefaults standardUserDefaults] 
                setObject:bookmarkId forKey:SRGeneralBookmark];
    }
    
    // Update bookmark text field
    [self _udpateBookmarkTextField];
}

- (void)closeBookmarkPanelAction:(id)sender
{
    // End sheet
    [NSApp endSheet:_bookmarkPanel returnCode:[sender tag]];
}

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

- (void)outlineView:(NSOutlineView*)outlineView 
        willDisplayCell:(id)cell 
        forTableColumn:(NSTableColumn*)column 
        item:(id)item
{
    // Bookmark outline
    if (outlineView == _bookmarkOutline) {
        // Get column identifier
        id  identifier;
        identifier = [column identifier];
        
        // For title column
        if ([identifier isEqualToString:@"title"]) {
            // Set image
            NSImage*    image = nil;
            if ([item respondsToSelector:@selector(observedObject)]) {
                image = [[item performSelector:@selector(observedObject)] valueForKey:@"icon"];
            }
            if (image) {
                [cell setImage:image];
            }
            
            return;
        }
    }
}

@end

//--------------------------------------------------------------//
#pragma mark -- Utility --
//--------------------------------------------------------------//

NSWindow* SRGetFrontBrowserWindow()
{
    // Get window number list
    int     count;
    int*    list;
    NSCountWindowsForContext((int)NULL, &count);
    list = malloc(sizeof(int) * count);
    NSWindowListForContext((int)NULL, sizeof(int) * count, list);
    
    // Find browser window
    Class       browserControllerClass;
    NSWindow*   window = nil;
    int         i;
    browserControllerClass = NSClassFromString(@"SRBrowserController");
    for (i = 0; i < count; i++) {
        // Get window
        window = [NSApp windowWithWindowNumber:list[i]];
        if (!window) {
            continue;
        }
        
        // Get window controller
        id  windowController;
        windowController = [window windowController];
        if ([windowController isKindOfClass:browserControllerClass]) {
            break;
        }
    }
    
    free(list);
    
    return window;
}
