//
//  ConfigurationManager.m
//  Etokicho
//
//  Created by 二鏡 on 11/11/25.
//  Copyright 2011年 二鏡庵. All rights reserved.
//

#import "ConfigurationManager.h"

NSString *ConfigurationManagerInitilizeFailureException = @"ConfigurationManagerInitilizeFailureException";
@implementation ConfigurationManager
@synthesize context;

+ (NSURL*)_URL
{
    id error;
    id fm = [NSFileManager defaultManager];
    id appSupport = [fm URLForDirectory: NSApplicationSupportDirectory
                               inDomain: NSUserDomainMask
                      appropriateForURL: nil
                                 create: YES
                                  error: &error];
    id folder = [appSupport URLByAppendingPathComponent: @"Etokicho"];
    [fm createDirectoryAtURL: folder withIntermediateDirectories: YES
                  attributes: nil
                       error: &error];
    return [folder URLByAppendingPathComponent: @"configuration.db"];
}

- (void)_setupInitialState
{
    id error;
    // 空ならnoneとnew transition...を追加
    id fetch = [NSFetchRequest fetchRequestWithEntityName: @"QCTransition"];
    id array = [context executeFetchRequest: fetch error: &error];
    if(array == nil)
    {
        [NSException exceptionWithName: ConfigurationManagerInitilizeFailureException
                                reason: @"Fetch request did failure at early state."
                              userInfo: nil];
    }
    
    if([array count] == 0)
    {        
        id entity = [NSEntityDescription entityForName: @"TransitionSetting"
                             inManagedObjectContext: context];
        id setting = [[NSManagedObject alloc] initWithEntity: entity
                              insertIntoManagedObjectContext: context];
        [setting release];
    }
}

- (id)init
{
    self = [super init];
    if (self) {
        id error;
        
        id URL = [[NSBundle mainBundle] URLForResource: @"ConfigurationDB" withExtension: @"momd"];
        id model = [[[NSManagedObjectModel alloc] initWithContentsOfURL: URL] autorelease];
        if(model == nil)
        {
            [self autorelease];
            return nil;
        }
        id coord = [[[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: model] autorelease];
        if([coord addPersistentStoreWithType: NSSQLiteStoreType
                               configuration: nil
                                         URL: [[self class] _URL]
                                     options: nil
                                       error: &error] == NO)
        {
            [NSApp presentError: error];
            [self autorelease];
            return nil;
        }
        context = [[NSManagedObjectContext alloc] init];
        [context setPersistentStoreCoordinator: coord];
        [self _setupInitialState];
    }
    
    return self;
}

- (void)dealloc
{
    [context release];
    [super dealloc];
}

- (NSManagedObject*)currentTransition
{
    id fetch = [NSFetchRequest fetchRequestWithEntityName: @"TransitionSetting"];
    id error;
    id setting = [[context executeFetchRequest: fetch
                                         error: &error] objectAtIndex: 0];
    return [setting valueForKey: @"default"];
}

- (void)setCurrentTransition:(NSManagedObject*)obj
{
    id fetch = [NSFetchRequest fetchRequestWithEntityName: @"TransitionSetting"];
    id error;
    id setting = [[context executeFetchRequest: fetch
                                         error: &error] objectAtIndex: 0];
    [setting setValue: obj forKey: @"default"];
}

- (NSManagedObject*)insertNewTransition
{
    id entity = [NSEntityDescription entityForName: @"QCTransition"
                            inManagedObjectContext: context];
    id ret = [[NSManagedObject alloc] initWithEntity: entity
                      insertIntoManagedObjectContext: context];
    return [ret autorelease];
}

- (NSManagedObject*)fetchItem:(id)container
{
    id objID = [container objectID];
    if(objID == nil)
        return nil;
    return [context objectWithID: objID];
}

- (void)deleteItem:(id)container
{
    id objID = [container objectID];
    id obj = [context objectWithID: objID];
    [context deleteObject: obj];
}

- (BOOL)save:(NSError**)error
{
    return [context save: error];
}

#pragma mark Transition
- (NSArray*)transitions
{
    id fetch = [NSFetchRequest fetchRequestWithEntityName: @"QCTransition"];
    id sorts = [NSArray arrayWithObject: [NSSortDescriptor sortDescriptorWithKey: @"name"
                                                                       ascending: YES]];
    [fetch setSortDescriptors: sorts];
    id error;
    id ret = [context executeFetchRequest: fetch 
                                    error: &error];
    return ret;
}

@end
