//
//  GyroView.m
//
//  Created by Patrick McNeil on 10-05-21.
//  Copyright 2010 Phidgets Inc.. All rights reserved.
//

#import "GyroView.h"

static inline CGRect
convertToCGRect(NSRect rect)
{
    return CGRectMake(rect.origin.x, rect.origin.y,
					  rect.size.width, rect.size.height);
}

@implementation GyroView

- (id)initWithFrame:(NSRect)frameRect
{
    if(self = [super initWithFrame:frameRect])
	{
		circleRadius = 1.0;
		xaxis = 0;
		yaxis = 0;
		zaxis = 0;
	}
	
    return self;
}

- (void)drawRect:(NSRect)re
{
    float w, h, r;
    CGRect rect;
    CGContextRef context;
	
    rect = convertToCGRect(re);
    context = [[NSGraphicsContext currentContext] graphicsPort];
	
	w = CGRectGetWidth(rect);
	h = CGRectGetHeight(rect);
	r = (w < h) ? w/3.0 : h/3.0;
    
	CGContextSetRGBStrokeColor(context, 1.0, 0, 0, 1);
	CGContextAddArc(context, CGRectGetMidX(rect), CGRectGetMidY(rect), r, (xaxis+2)*(M_PI/180), (xaxis-2)*(M_PI/180), false);
	CGContextStrokePath(context);
	
	CGContextAddArc(context, r*cos(xaxis*(M_PI/180)) + CGRectGetMidX(rect), r*sin(xaxis*(M_PI/180)) + CGRectGetMidY(rect), 4, 0, 2*M_PI, false);
	CGContextSetRGBFillColor(context, 0, 0, 0, 1);
	CGContextFillPath(context);
	
	CGContextSetRGBStrokeColor(context, 0, 1.0, 0, 1);
	CGContextAddArc(context, CGRectGetMidX(rect), CGRectGetMidY(rect), r-10, (yaxis+2)*(M_PI/180), (yaxis-2)*(M_PI/180), false);
	CGContextStrokePath(context);
	
	CGContextAddArc(context, (r-10)*cos(yaxis*(M_PI/180)) + CGRectGetMidX(rect), (r-10)*sin(yaxis*(M_PI/180)) + CGRectGetMidY(rect), 4, 0, 2*M_PI, false);
	CGContextSetRGBFillColor(context, 0, 0, 0, 1);
	CGContextFillPath(context);
	
	CGContextSetRGBStrokeColor(context, 0, 0, 1.0, 1);
	CGContextAddArc(context, CGRectGetMidX(rect), CGRectGetMidY(rect), r-20, (zaxis+2)*(M_PI/180), (zaxis-2)*(M_PI/180), false);
	CGContextStrokePath(context);
	
	CGContextAddArc(context, (r-20)*cos(zaxis*(M_PI/180)) + CGRectGetMidX(rect), (r-20)*sin(zaxis*(M_PI/180)) + CGRectGetMidY(rect), 4, 0, 2*M_PI, false);
	CGContextSetRGBFillColor(context, 0, 0, 0, 1);
	CGContextFillPath(context);
}

- (void)setHeadings:(double)x:(double)y:(double)z
{
	xaxis = x;
	yaxis = y;
	zaxis = z;
	
    [self setNeedsDisplay:YES];
}

- (void)setCircleRadius:(double)c
{
	circleRadius = c;
	
    [self setNeedsDisplay:YES];
}

@end
