/*
 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 "TiltAndSwipePad.h"
#import "ac_util.h"
#import "util.h"

#define SWIPES_CENTER_INTERVAL_SECONDS 0.05

@implementation TiltAndSwipePad

- (id)initWithFrame:(CGRect)frame andProcessor:(ModelProcessor*) p {
    CGRect f = frame;
    
    self = [super initWithFrame:f];
    if (self) {
        
        processor = [p retain];
        
        [self setBackgroundColor:[UIColor clearColor]];
        
        swipeInProgress=NO;
		swipeXSpring = 0.015;
		swipeYSpring = 0.015;
        
        [[UIAccelerometer sharedAccelerometer] setDelegate:self];
        [[UIAccelerometer sharedAccelerometer] setUpdateInterval:(0.01)];
        
        swipesFloatToCenterTimer = [NSTimer scheduledTimerWithTimeInterval: SWIPES_CENTER_INTERVAL_SECONDS
                                                                    target: self
                                                                  selector: @selector(swipesFloatToCenterMaybe)
                                                                  userInfo: nil
                                                                   repeats: YES];
    }
    return self;
}

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


// accelerometer input

- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {	
	float as = [processor accelerometerSensitivity];
    static int invert = 0;
    if (invert==0) {
        invert = device_has_audio_jack_on_bottom() ? -1 : 1;
    }
	[tiltXSink setValue: [tiltXSink value] * (1.0-as) + asin(clip(invert*acceleration.x, -1.0, 1.0))/M_PI_2 * as];
	[tiltYSink setValue: [tiltYSink value] * (1.0-as) + asin(clip(invert*acceleration.y, -1.0, 1.0))/M_PI_2 * as];
    
    // it feels resource-intensive to do this 100 times per second, but seems to work fine
    [self setNeedsDisplay];
}


// touch input

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
	swipeInProgress = YES;
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {    
	// I expect that it's already YES on account of a TouchDown before the
	// Drag, but set it just in case
	swipeInProgress = YES;
	
	UITouch *touch = [touches anyObject];
	UIView *container = [touch view];
	
	float containerHeight = container.bounds.size.height;
	float offsetInContainerY = [touch locationInView: container].y;
	float previousOffsetInContainerY = [touch previousLocationInView: container].y;
	float deltaY = (previousOffsetInContainerY - offsetInContainerY) / containerHeight;
	[swipeYSink setValue: [swipeYSink value] + 1.2 * deltaY];
	
	float containerWidth = container.bounds.size.width;
	float offsetInContainerX = [touch locationInView: container].x;
	float previousOffsetInContainerX = [touch previousLocationInView: container].x;
	float deltaX = (previousOffsetInContainerX - offsetInContainerX) / containerWidth;
	[swipeXSink setValue: [swipeXSink value] - 1.5 * deltaX];
    
    
    [self setNeedsDisplay];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
	swipeInProgress = NO;
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
	swipeInProgress = NO;
}

- (IBAction) swipePadDrag:(id) sender withEvent:(UIEvent *) event {
}

// autocentering
- (void) swipesFloatToCenterMaybe {
	//[tsvc doDisplayThing];  // move to drawRect?
	if (swipeInProgress) {
		// swipes float toward center only when user is not dragging finger across them
		return;
	}
	float x = [swipeXSink value];
	float xTrim = 0; //[swipeXSink trim];
	if(swipeXSpring && x!=xTrim) {
		if(fabs(x - xTrim) < swipeXSpring) {
			[swipeXSink setValue: xTrim];
		} else {
			[swipeXSink setValue: x - copysign(swipeXSpring, x - xTrim)];
		}
        [self setNeedsDisplay];
	}
	float y = [swipeYSink value];
	float yTrim = 0; //[swipeYSink trim];
	if (swipeYSpring && y!=yTrim) {
		if(fabs(y - yTrim) < swipeYSpring) {
			[swipeYSink setValue: yTrim];
		} else {
			[swipeYSink setValue: y - copysign(swipeYSpring, y - yTrim)];
		}
        [self setNeedsDisplay];
	}
}


- (NSString*) gerund {
	// override in subclass
	return nil;
}

- (TrimmerView*) trimmerForQuadrant:(enum quadrant) q {
    ModelProcessorChannel* c=nil;
	switch (q) {
		case Q_TOP:
            c=tiltXSink;
			break;
		case Q_RIGHT:
            c=tiltYSink;
			break;
		case Q_BOTTOM:
            c=swipeXSink;
			break;
		case Q_LEFT:
			c=swipeYSink;
            break;
	}
    return [[[TrimmerView alloc] initWithSwipePad:self andChannel:c inQuadrant:q] autorelease];
}

- (void)drawRect:(CGRect)rect {
    NSLog(@"redrawing");
}


@end
