/*
SRSearchEngine.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 "SRSearchEngine.h"
#import "SRSearchEngineConverter.h"

#import "SRConstants.h"

@implementation SRSearchEngineConverter : NSObject

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

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

//--------------------------------------------------------------//
#pragma mark -- Controller --
//--------------------------------------------------------------//

- (id<SRAppController>)appController
{
    return _appController;
}

- (void)setAppController:(id<SRAppController>)appController
{
    _appController = appController;
}

//--------------------------------------------------------------//
#pragma mark -- Conversion --
//--------------------------------------------------------------//

- (void)_convertShiira1SearchEngines:(NSArray*)searchEngines withParent:(SRSearchEngine*)parent
{
    // Get managed object context
    NSManagedObjectContext* context;
    id                      store;
    context = [_appController managedObjectContext];
    store = [_appController persistentStore];
    
    // Convert search engines
    int             index = 0;
    NSEnumerator*   enumerator;
    NSDictionary*   searchEngineDict;
    enumerator = [searchEngines objectEnumerator];
    while (searchEngineDict = [enumerator nextObject]) {
        // Decide search engine type
        NSString*   type;
        type = SRSearchEngineTypeEngine;
        if ([[searchEngineDict objectForKey:@"isSeparator"] boolValue]) {
            type = SRSearchEngineTypeSeparator;
        }
        if ([searchEngineDict objectForKey:@"children"]) {
            type = SRSearchEngineTypeFolder;
        }
        
        // Create search engine
        SRSearchEngine* searchEngine;
        searchEngine = [NSEntityDescription insertNewObjectForEntityForName:@"SearchEngine" 
                inManagedObjectContext:context];
        [context assignObject:searchEngine toPersistentStore:store];
        [searchEngine setValue:type forKey:@"type"];
        [searchEngine setValue:parent forKey:@"parent"];
        [searchEngine setValue:[NSNumber numberWithInt:index++] forKey:@"index"];
        [[parent valueForKey:@"children"] addObject:searchEngine];
        
        // For engine
        if (type == SRSearchEngineTypeEngine) {
            [searchEngine setValue:[searchEngineDict objectForKey:@"title"] forKey:@"title"];
            [searchEngine setValue:[searchEngineDict objectForKey:@"templateURL"] forKey:@"templateURL"];
            [searchEngine setValue:[searchEngineDict objectForKey:@"keyword"] forKey:@"keyword"];
            [searchEngine setValue:[searchEngineDict objectForKey:@"encoding"] forKey:@"encoding"];
            [searchEngine setValue:[searchEngineDict objectForKey:@"isUsing"] forKey:@"isUsing"];
        }
        
        // For separator
        if (type == SRSearchEngineTypeSeparator) {
            [searchEngine setValue:@"--------" forKey:@"title"];
        }
        
        // For folder
        if (type == SRSearchEngineTypeFolder) {
            [searchEngine setValue:[searchEngineDict objectForKey:@"title"] forKey:@"title"];
            
            // Convert children
            [self _convertShiira1SearchEngines:[searchEngineDict objectForKey:@"children"] 
                    withParent:searchEngine];
        }
    }
}

- (void)convertSearchEnginesOfShiira1
{
    // Create path ~/Library/Shiira/SearchEngines.plist
    NSArray*    libraryPaths;
    NSString*	searchEnginesPath = nil;
    libraryPaths = NSSearchPathForDirectoriesInDomains(
            NSLibraryDirectory, NSUserDomainMask, YES);
    if ([libraryPaths count] > 0) {
        searchEnginesPath = [[libraryPaths objectAtIndex:0] stringByAppendingPathComponent:
                [NSString stringWithFormat:@"Shiira/%@", SRSearchEnginesFileName]];
    }
    if (!searchEnginesPath) {
        return;
    }
    
    // Read search engine plist
    NSArray*    searchEngines = nil;
    NSData*     data;
    if ([[NSFileManager defaultManager] fileExistsAtPath:searchEnginesPath]) {
        data = [NSData dataWithContentsOfFile:searchEnginesPath];
        searchEngines = [NSPropertyListSerialization propertyListFromData:data 
                mutabilityOption:0 format:NULL errorDescription:NULL];
    }
    if (!searchEngines) {
        return;
    }
    
    // Convert serch engines
    [self _convertShiira1SearchEngines:searchEngines withParent:nil];
}

@end
