//
//  MPT_ElanExportAll.m
//  AUCoderDemo
//
//  Created by Andrew Salamon on 1/5/10.
//  Copyright 2010 Machine Perception Laboratory, University of California San Diego.. All rights reserved.
//

#import "MPT_ElanExportAll.h"

@interface MPT_ElanExportAll(PrivateMethods)
- (NSString *)recordDataPoint:(NSDictionary *)pluginResults usingPlugins:(NSArray *)plugins;
@end

@implementation MPT_ElanExportAll
+ (BOOL)handlesReading
{
	return NO;
}
+ (BOOL)handlesWriting
{
	return YES;
}
+ (NSString *)preferredExtension
{
    return @"csv";
}

- (id)init
{
	self = [super init];
	pluginsToExport = [[NSArray alloc] initWithObjects:@"edu.ucsd.mplab.plugins.CERT4_4_Weights", @"edu.ucsd.mplab.plugins.SmileDetector2", nil];
	return self;
}

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

- (NSArray *)pluginsToExport {
    return [[pluginsToExport retain] autorelease];
}

- (void)setPluginsToExport:(NSArray *)value {
    if (pluginsToExport != value) {
        [pluginsToExport release];
        pluginsToExport = [value copy];
    }
}

- (BOOL)writeResults:(NSArray *)resultsArray toFile:(NSString *)path usingController:(id<MPT_PluginControllerProtocol>)pluginController
{
	NSEnumerator *resEnum = [resultsArray objectEnumerator];
	NSDictionary *oneRes = nil;
	NSMutableString *output = [NSMutableString string];
	const float oneFrame = 1.0 / [MPT_DocumentController framerateFromResults:resultsArray];
	float start = 0.0;

	NSMutableArray *plugins = [NSMutableArray array];
	NSEnumerator *pluginEnum = [pluginsToExport objectEnumerator];
	NSString *pluginID;
	while( pluginID = [pluginEnum nextObject] )
	{		
		id onePlugin = [pluginController pluginForPluginID:pluginID];
		if( onePlugin && [onePlugin enabled] )
		{
			[plugins addObject:onePlugin];
		}
		else
		{
			NSLog( @"Error in MPT_ElanExportAll. Missing plugin: %@", pluginID );
		}
	}
	
    while( oneRes = [resEnum nextObject] )
    {
		NSString *tmp = [self recordDataPoint:oneRes usingPlugins:plugins];
		[output appendFormat:@"%f%@\n", start, tmp];
		start += oneFrame;
	}
	
    return [output writeToFile:path atomically:NO];
}

//- (BOOL)writeResults:(NSArray *)resultsArray toFile:(NSString *)path usingController:(id<MPT_PluginControllerProtocol>)pluginController
//{
//	//    const int avgPref = 10;
//	const float oneFrame = 1.0 / 30.0;
//	
//    NSMutableString *output = [NSMutableString string];
//    int index = 0;
//    int cnt = [resultsArray count];
//    
//    float start = 0.0;
//	//    float end = 0.0;
//    
//    while( index < cnt )
//    {
//        float joy = 0.0;
//        float perc = 0.0;
//        float odds = 0.0;
//        int avgCnt = 1;
//		//        for( ; (avgCnt < avgPref) && (index < cnt); ++avgCnt, ++index )
//        {
//            NSDictionary *pluginResults = [resultsArray objectAtIndex:index];
//            
//            NSDictionary *plugin = [pluginResults objectForKey:@"com.mpt4u.plugins.Enjoyment"];
//            NSNumber *val = [plugin objectForKey:@"JoyQuotient"];
//            if( plugin && val )
//            {
//                joy += [val floatValue];
//            }
//			
//            plugin = [pluginResults objectForKey:@"com.mpt4u.plugins.JoyPercentile"];
//            val = [plugin objectForKey:@"Percentile"];
//            if( plugin && val )
//            {
//                perc += [val floatValue];
//            }
//            
//            plugin = [pluginResults objectForKey:@"com.mpt4u.plugins.Odds"];
//            val = [plugin objectForKey:@"Odds"];
//            if( plugin && val )
//            {
//                odds += [val floatValue];
//            }
//        }
//        
//        // Take a look at Figure 4.32. The first row represents the event of a person saying 'so from here'. The first value (as well as the first column of the complete file) represents the tier name, the second and third represent begin time in different formats, the fourth and fifth represent the end time, the sixth an seventh represent the duration and the last value represents the annotation.
//        
//		[output appendFormat:@"%f\t%f\t%f\t%f\n", start, (joy / ((float)avgCnt)), (perc / ((float)avgCnt)), (odds / ((float)avgCnt))];
//		
//		start += oneFrame;
//		++index;        
//    }
//	
//    return [output writeToFile:path atomically:NO];
//}
- (NSArray *)resultsFromFile:(NSString *)path
{
	return nil;
}

- (NSString *)recordDataPoint:(NSDictionary *)pluginResults usingPlugins:(NSArray *)plugins
{
	// Walk through all plugins and output results if they are enabled
	NSMutableString *pluginString = [NSMutableString string];
	
	NSEnumerator *pluginEnum = [plugins objectEnumerator];
	id<MPT_PluginProtocol> plugin;
	while( plugin = [pluginEnum nextObject] )
	{
		id resNum = [pluginResults objectForKey:[plugin pluginID]];
		
		if( [[plugin labels] count] > 1 )
		{
			NSString *label;
			NSEnumerator *labelEnum = [[plugin labels] objectEnumerator];
			while( label = [labelEnum nextObject] )
			{
				id value = [resNum objectForKey:label];
				if( value && [value isKindOfClass:[NSNumber class]] )
				{
					[pluginString appendFormat:@"\t%f", [value floatValue]];
				}
				else
				{
					[pluginString appendString:@"\tNaN"];
				}
			}
		}
		else
		{
			if( resNum && [resNum isKindOfClass:[NSNumber class]] )
			{
				[pluginString appendFormat:@"\t%f", [resNum floatValue]];
			}
			else
			{
				[pluginString appendString:@"\tNaN"];
			}
		}
	}
//	if( ([pluginString length] > 0) && ('\t' == [pluginString characterAtIndex:0]) )
//		[pluginString deleteCharactersInRange:NSMakeRange(0,1)];
	
	return pluginString;
}

@end
