//
//  MainView.m
//  BalanceBall
//
//  Created by Chris Adamson on 6/15/09.
//  Copyright Subsequently and Furthermore, Inc. 2009. All rights reserved.
//
//
//  Licensed with the Apache 2.0 License
//  http://apache.org/licenses/LICENSE-2.0
//


#import "MainView.h"

@implementation MainView

@synthesize shakeDelegate;

- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        // Initialization code
    }
    return self;
}

//START:code.BalanceBall.MainView.setBallWidthHeight
- (void) setBallWidth: (CGFloat) newW height: (CGFloat) newH {
	ballRect.size.width = newW;
	ballRect.size.height = newH;
	oldBallRect.size.width = newW;
	oldBallRect.size.height = newH;
}
//END:code.BalanceBall.MainView.setBallWidthHeight

//START:code.BalanceBall.MainView.setBallXY
-(void) setBallX: (CGFloat) newX Y: (CGFloat) newY {
	ballRect.origin.x = newX;
	ballRect.origin.y = newY;
	
	// update view
	CGRect clipRect = CGRectUnion (oldBallRect, ballRect);
	[self setNeedsDisplayInRect:clipRect];
	
	// update oldBallRect
	oldBallRect.origin.x = ballRect.origin.x;
	oldBallRect.origin.y = ballRect.origin.y;
}
//END:code.BalanceBall.MainView.setBallXY

//START:code.BalanceBall.MainView.drawRect
- (void)drawRect:(CGRect)rect {
	// Drawing code
	CGContextRef context = UIGraphicsGetCurrentContext();
	
	// undraw ball at old location
	CGColorRef undrawColor = self.backgroundColor.CGColor;
	CGContextSetFillColorWithColor (context, undrawColor);
	CGContextFillRect (context, oldBallRect);
	
	// draw ball at new location
	CGContextSetGrayFillColor(context, 1.0, 1.0);
	CGContextFillEllipseInRect(context, ballRect);
}
//END:code.BalanceBall.MainView.drawRect


# pragma new-for-3.0 UIResponder motion events
//START:code.BalanceBall.MainView.motionbegan
-(BOOL) canBecomeFirstResponder {
	return YES;
}
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event {
	[super motionBegan: motion withEvent: event];
	if ((motion == UIEventSubtypeMotionShake) &&
		[self.shakeDelegate respondsToSelector:
			@selector (shakeMotionBegan:)]) {
		[self.shakeDelegate shakeMotionBegan: event];
	}
}
//END:code.BalanceBall.MainView.motionbegan

/* we don't use these events, but they're included for your information
- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event {
	[super motionCancelled: motion withEvent: event];
}
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
	[super motionEnded: motion withEvent: event];
}
*/


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


@end
