/*
iPhly: Radio Control on the iPhone

Copyright (C) 2010-2011 Ari Krupnik & Associates

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License V2
as published by the Free Software Foundation.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

#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;
		[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);
	
	// a bunch of kludges for to support two-servo wings and FPV head trackers without user-configurable mixes
	if ([[self name] isEqual:@"aileron"]) {
		ppm_audio_out_set_value_to_transmit(4, outputValue * -1.0);
		ppm_audio_out_set_value_to_transmit(5, outputValue * -1.0);
		ppm_audio_out_set_value_to_transmit(6, outputValue);
	} else if ([[self name] isEqual:@"elevator"]) {
		ppm_audio_out_set_value_to_transmit(7, 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];
	[super dealloc];
}

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

@end

