/*
SRBrowserMenuProvider.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 "SRMenu.h"

#import "SRBrowserMenuProvider.h"

@implementation SRBrowserMenuProvider

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

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

@end

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

NSArray* SRBrowserIds(BOOL containsShiira)
{
    // Get self identifier
    NSString*   shiiraIdentifier;
    shiiraIdentifier = [[NSBundle mainBundle] bundleIdentifier];
    
    // Get application identifiers for HTTP
    NSArray*        allBrowserIds;
    NSMutableArray* browserIds;
    allBrowserIds = (NSArray*)LSCopyAllHandlersForURLScheme(CFSTR("http"));
    browserIds = [NSMutableArray arrayWithArray:allBrowserIds];
    [allBrowserIds release];
    
    // Remove or add itself
    if ([browserIds containsObject:shiiraIdentifier]) {
        if (!containsShiira) {
            [browserIds removeObject:shiiraIdentifier];
        }
    }
    else {
        if (containsShiira) {
            [browserIds addObject:shiiraIdentifier];
        }
    }
    
    return browserIds;
}

NSArray* SRBrowserMenuItems(BOOL containsShiira)
{
    NSWorkspace*    workspace;
    workspace = [NSWorkspace sharedWorkspace];
    
    // Get browser IDs
    NSArray*    browserIds;
    browserIds = SRBrowserIds(containsShiira);
    
    // Check there are two or more Shiira
    int             countOfShiira = 0;
    NSEnumerator*   enumerator;
    NSString*       browserId;
    enumerator = [browserIds objectEnumerator];
    while (browserId = [enumerator nextObject]) {
        if ([browserId hasSuffix:@"shiira"] || [browserId hasSuffix:@"Shiira"]) {
            countOfShiira++;
        }
    }
    
    // Create menu items
    NSMutableArray* menuItems;
    menuItems = [NSMutableArray array];
    enumerator = [browserIds objectEnumerator];
    while (browserId = [enumerator nextObject]) {
        NSString*   browserPath;
        NSString*   browserURL;
        NSString*   browserName;
        OSStatus    status;
        browserPath = [workspace absolutePathForAppBundleWithIdentifier:browserId];
        if (!browserPath) {
            continue;
        }
        
        browserURL = [NSURL fileURLWithPath:browserPath];
        status = LSCopyDisplayNameForURL((CFURLRef)browserURL, (CFStringRef*)&browserName);
        if (status == noErr) {
            // For shiira
            if (countOfShiira > 1 && ([browserId hasSuffix:@"shiira"] || [browserId hasSuffix:@"Shiira"])) {
                // Get version
                NSString*   version;
                version = [[[NSBundle bundleWithPath:browserPath] 
                        infoDictionary] objectForKey:@"CFBundleShortVersionString"];
                if (version) {
                    browserName = [NSString stringWithFormat:@"%@ %@", browserName, version];
                }
            }
            
            // Get icon for this app
            NSImage*    icon;
            icon = [workspace iconForFile:browserPath];
            [icon setSize:NSMakeSize(16, 16)];
            
            // Create menu item
            NSMenuItem* menuItem;
            menuItem = [[NSMenuItem alloc] 
                    initWithTitle:browserName action:@selector(openURLWithAction:) keyEquivalent:@""];
            [menuItem autorelease];
            [menuItem setTag:SROpenURLWithBrowserItemTag];
            [menuItem setRepresentedObject:browserId];
            if (icon) {
                [menuItem setImage:icon];
            }
            
            // Add menu item
            [menuItems addObject:menuItem];
        }
    }
    
    // Sort menu items
    NSSortDescriptor*   sortDescriptor;
    sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"title" ascending:YES];
    [menuItems sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
    [sortDescriptor release];
    
    return menuItems;
}
