//
//  MPT_ElanExport_csv.m
//  AUCoderDemo
//
//  Created by Andrew Salamon on 11/11/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "MPT_ElanExport_csv.h"
#import "MPT_ElanExport_eaf.h"

@implementation MPT_ElanExport_csv
+ (BOOL)handlesReading
{
	return NO;
}
+ (BOOL)handlesWriting
{
	return YES;
}
+ (NSString *)preferredExtension
{
    return @"csv";
}
- (BOOL)writeResults:(NSArray *)resultsArray toFile:(NSString *)path
{
//    const int avgPref = 10;
	const float oneFrame = 1.0 / [[self class] framerateFromResults:resultsArray];
	
    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 *oneRes = [resultsArray objectAtIndex:index];
            
            NSDictionary *plugin = [oneRes objectForKey:@"com.mpt4u.plugins.Enjoyment"];
            NSNumber *val = [plugin objectForKey:@"JoyQuotient"];
            if( plugin && val )
            {
                joy += [val floatValue];
            }

            plugin = [oneRes objectForKey:@"com.mpt4u.plugins.JoyPercentile"];
            val = [plugin objectForKey:@"Percentile"];
            if( plugin && val )
            {
                perc += [val floatValue];
            }
            
            plugin = [oneRes 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;
//       start = end;
//        end += 1.0;
//        [output appendFormat:@"%@\t00:00:00.000\t%f\t00:00:00.000\t%f\t00:00:01.00\t1.0\t%f\n", @"Joy Quotient", start, end, (joy / ((float)avgCnt))];
//        [output appendFormat:@"%@\t00:00:00.000\t%f\t00:00:00.000\t%f\t00:00:01.00\t1.0\t%f\n", @"Percentile", start, end, (perc / ((float)avgCnt))];
//        [output appendFormat:@"%@\t00:00:00.000\t%f\t00:00:00.000\t%f\t00:00:01.00\t1.0\t%f\n", @"Odds", start, end, (odds / ((float)avgCnt))];
		
    /*
    "com.mpt4u.plugins.Enjoyment" =     {
        Enjoyment = -4.060863;
        JoyQuotient = 77.66933;
        cutoff = 100;
    };
    "com.mpt4u.plugins.JoyPercentile" =     {
        Percentile = 17.89546;
        cutoff = 50;
    };
    "com.mpt4u.plugins.Odds" =     {
        Odds = -2.541857;
        cutoff = 1;
    };
    */
        
    }

	NSString *origExt = [path pathExtension];
	if( [origExt isEqualToString:@"txt"] )
	{
		// Uh, oh. User switched to the wrong extension. 'fix' it for them
		path = [[path stringByDeletingPathExtension] stringByAppendingPathExtension:@"csv"];
	}
	
	// For ASAP we want to write out both Elan file types at the same time. Same file name and location, different extensions (.csv and .eaf).
    BOOL written = [output writeToFile:path atomically:NO];
	BOOL written2 = NO;
	
	path = [[path stringByDeletingPathExtension] stringByAppendingPathExtension:@"txt"];
	MPT_ElanExport_eaf *eafWriter = [[[MPT_ElanExport_eaf alloc] init] autorelease];
	written2 = [eafWriter writeResults:resultsArray toFile:path];
	return (written && written2);
}

- (NSArray *)resultsFromFile:(NSString *)path
{
	return nil;
}

+ (float)framerateFromResults:(NSArray *)resultsArray
{
	float framerate = 30.0;
	if( [resultsArray count] > 0 )
	{
		NSDictionary *firstRes = [resultsArray objectAtIndex:0];
		NSString *path = [firstRes objectForKey:@"CERT.path"];
		NSMutableArray *pathComps = [[[path componentsSeparatedByString:@":"] mutableCopy] autorelease];
		if( [pathComps count] > 1 )
		{
			[pathComps removeLastObject];
			path = [pathComps componentsJoinedByString:@":"];
		}
		NSError *error = nil;
		QTMovie *movie = [QTMovie movieWithFile:path error:&error];
		if( !error )
		{
			QTTime dur = [movie duration];
			NSTimeInterval seconds;
			if( QTGetTimeInterval( dur, &seconds ) )
			{
				float tmpRate = [resultsArray count] / seconds;
				if( (tmpRate > 0.0) && (tmpRate < 600.00) ) // arbitrary upper limit
					framerate = tmpRate;
			}
		}
	}
	return framerate;
}
@end



