//
//  ModelProcessor.m
//  iPhly
//
//  Created by Ari Krupnik on 5/4/10.
//  Copyright 2010 lib.aero. All rights reserved.
//

#import "ModelProcessor.h"
#import "NSMutableDictionary+ModelConfig.h"
#import "ModelProcessorChannel.h"
#import "ppm_audio_out.h"


NSString * const MODEL_CONFIG_FILE_EXTENSION = @"aero";

@implementation ModelProcessor

+ (NSString *) modelsDir {
	NSString *documentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
	return [documentsDir stringByAppendingPathComponent: @"models"];
}

+ (NSArray *) allModelPaths {
	NSMutableArray *modelPaths = [[NSMutableArray alloc] init];
	for (NSString *fileName in [[NSFileManager defaultManager] contentsOfDirectoryAtPath: [ModelProcessor modelsDir] error: NULL]) {
		if ([[fileName pathExtension] isEqualToString:MODEL_CONFIG_FILE_EXTENSION]) {
			[(NSMutableArray *) modelPaths addObject: [[ModelProcessor modelsDir] stringByAppendingPathComponent: fileName]];
		}
	}
	[modelPaths autorelease];
	return modelPaths;
}



- (ModelProcessor *) initWithFilePath: (NSString *) path {
    self = [super init];
    if ( self ) {
		filePath = path;
		[filePath retain];
		data = [[NSMutableDictionary alloc] initWithContentsOfFile: filePath];
		
		accelerometerSensitivity = [data accelerometerSensitivity];
		
		channels = [[NSMutableArray alloc] init];
		
		for (int i=0; i<[data numChannels]; i++) {
			ModelProcessorChannel *pc = [[ModelProcessorChannel alloc] initWithProcessor: self andOrd:i];
			[channels addObject: pc];
			[pc release];
		}
		
		ppm_audio_out_init([self numChannels]);
	}
	return self;
}

- (NSString *) name {
	return [[filePath lastPathComponent] stringByDeletingPathExtension];
}

- (void) setName: (NSString *) name {
	// check that name is different (return silently if same)
	// check that name is legal, modify if isn't
	// check that file doesn't exist already
}

- (BOOL) isAirplane {
	return [data isAirplane];
}
- (BOOL) isCar {
	return [data isCar];
}

- (int) numChannels {
	return [channels count];
}
- (ModelProcessorChannel *) channelAtIndex:(int) i {
	return [channels objectAtIndex: i];
}
- (ModelProcessorChannel *) channelByName:(NSString *) name {
	for (ModelProcessorChannel *c in channels) {
		if ([name isEqualToString: [c name]]) {
			return c;
		}
	}
	return nil;
}

- (void) setAccelerometerSensitivity:(float) n {
	[data setAccelerometerSensitivity:n];
	[self writeToFile];
}

@synthesize filePath;

@synthesize accelerometerSensitivity;

/*
@synthesize aileron;
@synthesize elevator;
@synthesize throttle;
@synthesize rudder;
*/

- (NSMutableDictionary *) __channelDataAtIndex:(int) i {
	return [data channel:i];
}

- (BOOL) writeToFile {
	return [data writeToFile: filePath atomically: YES];
}

- (void) dealloc {
	// stop audio
	[channels release];
	[data release];
	
	[filePath release];
	
	[super dealloc];
}

@end