//
//  OmPincher.m
//  OmLoc
//
//  Created by david van brink on 7/24/10.
//  Copyright 2010 omino.com. All rights reserved.
//

#import "OmPincher.h"


@implementation OmPincher

enum {
    OP_NOT_STARTED,
    OP_PINCHING,
    OP_DONE
};

#define OP_TOUCH_DIST_TO_START 80


-(void)begin:(NSSet *)touches view:(UIView *)newView
{
    self->state = OP_NOT_STARTED;
    
    self->current.pinching = false;
    self->current.ratio = 1.0;
    self->current.angle = 0.0;
    self->current.x = 0.0;
    self->current.y = 0.0;
    
    self->view = newView;
    
    [self move:touches];
}

static double dist(double x1,double y1,double x2,double y2)
{
    x1 -= x2;
    y1 -= y2;
    double d = sqrt(x1 * x1 + y1 * y1);
    return d;
}
// return true if the touches represent a pinch change
-(OmPinchData *)move:(NSSet *)touches
{
    int count = [touches count];
    if(state == OP_PINCHING && count != 2)
    {
        // no more as of now.
        state = OP_DONE;
    }
    
    if(state == OP_DONE)
    {
        // all done, no more.
        current.pinching = false;
        return &current;        
    }
    
    if(count != 2)
    {        
        // havnet started yet
        return &current;
    }
    
    // count is two...
    NSEnumerator *e = [touches objectEnumerator];
    UITouch *t1 = [e nextObject];
    UITouch *t2 = [e nextObject];
    CGPoint p1 = [t1 locationInView:view];
    CGPoint p2 = [t2 locationInView:view];
    
    if(state == OP_NOT_STARTED) // begin!
    {
        // begin only if the touches are far apart...
        double touchDist = dist(p1.x, p1.y, p2.x, p2.y);
        if(touchDist >= OP_TOUCH_DIST_TO_START)
        {
            self->x1 = p1.x;
            self->y1 = p1.y;
            self->x2 = p2.x;
            self->y2 = p2.y;
            state = OP_PINCHING;
            current.pinching = true;
        }
    }
    else if(state == OP_PINCHING) // continue!
    {
        self->xp1 = p1.x;
        self->yp1 = p1.y;
        self->xp2 = p2.x;
        self->yp2 = p2.y;
        
        double d = dist(self->x1,self->y1,self->x2,self->y2);
        double dPrime = dist(self->xp1,self->yp1,self->xp2,self->yp2);
        current.ratio = dPrime / d;
    }
    return &current;
    
}

-(OmPinchData *)current
{
    return &current;
}


@end
