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

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


@implementation ModelProcessorChannel

@synthesize value;
@synthesize reversing;
@synthesize trim;
@synthesize rate;
@synthesize ord;
@synthesize persistentData;

- (ModelProcessorChannel *) initWithProcessor: (ModelProcessor *) proc andOrd: (int) o {
    self = [super init];
    if ( self ) {
		ord = o;
		owner = proc;
		[owner retain];
		[self setPersistentData: [proc __channelDataAtIndex: ord]];
	}
	return self;
}

- (void) setPersistentData:(NSMutableDictionary *) data {
	reversing = [data reversing];
	trim = [data trim];
	rate = [data rate];
	[persistentData release];
	persistentData = data;
	[persistentData retain];
}

- (void) setValue:(float) v {
	value = clip(v, -1.0, 1.0);
	float outputValue = clip(value + trim, -1.0, 1.0);  // i can imagine other formulae for applying trim
	if (reversing) {
		outputValue = -outputValue;
	}
	outputValue *= rate;
	ppm_audio_out_set_value_to_transmit(ord, outputValue);
}

- (void) setTrim:(float) t {
	trim  = clip(t, -0.5, 0.5);
	[self setValue: [self value]]; // forces the new trim to take effect immediately
	[persistentData setTrim: t];
	[owner writeToFile];
}

- (void) setReversing:(BOOL) r {
	reversing = r;
	[persistentData setReversing: r];
	[owner writeToFile];
}

- (void) setRate:(float) r {
	rate = r;
	[persistentData setRate: r];
	[owner writeToFile];
}

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

- (NSString *) name {
	return [persistentData name];
}

@end

