/*
SRPlugInController.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 "SRAppController.h"

#import "SRPlugIn.h"
#import "SRPlugInController.h"

// Support file name
NSString*   SRPlugInsDirectoryName = @"Shiira Plug-Ins";

@implementation SRPlugInController

//--------------------------------------------------------------//
#pragma -- Plug-in path --
//--------------------------------------------------------------//

+ (NSString*)builtInPlugInPath
{
    NSString*   dirPath;
    dirPath = [[NSBundle mainBundle] builtInPlugInsPath];
    
    return dirPath;
}

+ (NSString*)userPlugInPath
{
    NSString*   dirPath;
    dirPath = HMApplicationSupportFolder(@"Shiira");
    dirPath = [dirPath stringByAppendingPathComponent:SRPlugInsDirectoryName];
    
    return dirPath;
}

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

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

- (id)init
{
    self = [super init];
    if (!self) {
        return nil;
    }
    
    // Initialize instance variables
    _plugInSchemes = [[NSMutableArray array] retain];
    
    return self;
}

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

//--------------------------------------------------------------//
#pragma -- Shiira plug in --
//--------------------------------------------------------------//

- (void)_loadShiiraPlugInsAtDirectory:(NSString*)dirPath
{
    // Check existense
    NSFileManager*	fileMgr;
    BOOL            isDir;
    fileMgr = [NSFileManager defaultManager];
    if (![fileMgr fileExistsAtPath:dirPath isDirectory:&isDir] || !isDir) {
        return;
    }
    
    // Load plug-ins
    NSEnumerator*   enumerator;
    NSString*       dirContent;
    enumerator = [[fileMgr directoryContentsAtPath:dirPath] objectEnumerator];
    while (dirContent = [enumerator nextObject]) {
        // Check extension
        NSString*   path;
        path = [dirPath stringByAppendingPathComponent:dirContent];
        if (![[path pathExtension] isEqualToString:@"plugin"]) {
            continue;
        }
        
        // Load bundle
        NSBundle*       bundle;
        NSDictionary*   infoDict;
        bundle = [[NSBundle alloc] initWithPath:path];
        if (![bundle load]) {
            // Error
            NSLog(@"Faield to load bundle, %@", path);
        }
        infoDict = [bundle infoDictionary];
        
        // Get plug-in class
        NSString*   plugInClassName;
        Class       plugInClass;
        plugInClassName = [infoDict objectForKey:@"NSPrincipalClass"];
        if (!plugInClassName) {
            continue;
        }
        plugInClass = NSClassFromString(plugInClassName);
        if (!plugInClass) {
            continue;
        }
        
        // Register plug-in
        [plugInClass registerPlugIn];
        
        [bundle release];
        
        // Add scheme
        NSString*   scheme;
        scheme = [infoDict objectForKey:@"SRPlugInScheme"];
        if (scheme) {
            NSURL*  url;
            url = [NSURL URLWithString:scheme];
            [_plugInSchemes addObject:[url scheme]];
        }
    }
}

- (void)loadShiiraPlugIns
{
    // Remove all schemes
    [_plugInSchemes removeAllObjects];
    
    // Find in main bundle
    NSString*   dirPath;
    dirPath = [[self class] builtInPlugInPath];
    [self _loadShiiraPlugInsAtDirectory:dirPath];
    
    // Create path ~/Library/Application Support/Shiira/Shiira Plug-Ins
    dirPath = [[self class] userPlugInPath];
    [self _loadShiiraPlugInsAtDirectory:dirPath];
}

- (void)_collectPlugInInfoDictsAtDirectory:(NSString*)dirPath intoArray:(NSMutableArray*)infoDicts
{
    // Check existense
    NSFileManager*	fileMgr;
    BOOL            isDir;
    fileMgr = [NSFileManager defaultManager];
    if (![fileMgr fileExistsAtPath:dirPath isDirectory:&isDir] || !isDir) {
        return;
    }
    
    // Get plug-ins
    NSEnumerator*   enumerator;
    NSString*       dirContent;
    enumerator = [[fileMgr directoryContentsAtPath:dirPath] objectEnumerator];
    while (dirContent = [enumerator nextObject]) {
        // Check extension
        NSString*   path;
        path = [dirPath stringByAppendingPathComponent:dirContent];
        if (![[path pathExtension] isEqualToString:@"plugin"]) {
            continue;
        }
        
        // Get info dict
        NSBundle*       bundle;
        NSDictionary*   infoDict;
        bundle = [[NSBundle alloc] initWithPath:path];
        if (![bundle load]) {
            // Error
            NSLog(@"Faield to load bundle, %@", path);
        }
        infoDict = [bundle infoDictionary];
        
        // Add info dict
        [infoDicts addObject:infoDict];
    }
}

- (NSArray*)plugInInfoDicts
{
    NSMutableArray* infoDicts;
    infoDicts = [NSMutableArray array];
    
    // Collect in main bundle
    NSString*   dirPath;
    dirPath = [[self class] builtInPlugInPath];
    [self _collectPlugInInfoDictsAtDirectory:dirPath intoArray:infoDicts];
    
    // Create path ~/Library/Application Support/Shiira/Shiira Plug-Ins
    dirPath = [[self class] userPlugInPath];
    [self _collectPlugInInfoDictsAtDirectory:dirPath intoArray:infoDicts];
    
    return infoDicts;
}

- (NSArray*)plugInSchemes
{
    return _plugInSchemes;
}

@end
