//
//  TransformationsViewController.m
//  Transformations
//
//  David J. Malan
//  Harvard University
//  dmalan@harvard.edu
//
//  Demonstrates affine transformations of Tommy.
//

#import "TransformationsViewController.h"

@implementation TransformationsViewController

@synthesize imageView=_imageView;
@synthesize scale=_scale;

- (void)handlePan:(UIPanGestureRecognizer *)sender
{
    // translate Tommy
    CGPoint translation = [sender translationInView:self.imageView];
    CGAffineTransform scale = CGAffineTransformMakeScale(self.scale, self.scale);
    CGAffineTransform translate = CGAffineTransformMakeTranslation(_translation.x + translation.x * self.scale, _translation.y + translation.y * self.scale);
    sender.view.transform = CGAffineTransformConcat(scale, translate);
    
    // remember translation once done panning
    if (sender.state == UIGestureRecognizerStateEnded) {
        _translation.x += translation.x * self.scale;
        _translation.y += translation.y * self.scale;       
    }
}

- (void)handlePinch:(UIPinchGestureRecognizer *)sender
{    
    // scale Tommy
    CGFloat factor = [sender scale];
    CGAffineTransform scale = CGAffineTransformMakeScale(self.scale * factor, self.scale * factor);
    CGAffineTransform translate = CGAffineTransformMakeTranslation(_translation.x, _translation.y);
    sender.view.transform = CGAffineTransformConcat(scale, translate);
    
    // remember scale once done pinching
    if (sender.state == UIGestureRecognizerStateEnded) {
        self.scale *= factor;
    }  
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // initial scale
    self.scale = 1.0;

    // initial translation
    _translation.x = 0.0;
    _translation.y = 0.0;

    // listen for pan
    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
    [self.imageView addGestureRecognizer:panGesture];
    [panGesture release];
    
    // listen for pinch
    UIPinchGestureRecognizer *pinchGesture = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handlePinch:)];
    [self.imageView addGestureRecognizer:pinchGesture];
    [pinchGesture release];   
}

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

@end
