#import  "RotateView.h"
#import  <math.h>
#import  <dpsclient/wraps.h>
#import  <appkit/NXImage.h>
#import  <appkit/Control.h>
#import  <appkit/TextField.h>
#import  "../common.h"
#import  "../ImageOpCtr.h"
#import  "imageOperation.h"

@implementation RotateView

/* Overload */
- initFrame:(const NXRect *)frameRect
{
	float	min;

	[super initFrame:frameRect];
	min = frameRect->size.width;
	if (min > frameRect->size.height) min = frameRect->size.height;
	xc = frameRect->size.width / 2.0;
	yc = frameRect->size.height / 2.0;
	x0 = min * -0.35;
	x1 = min * 0.35;
	y0 = min * -0.25;
	y1 = min * 0.25;
	[self drawIt: nil];
	return self;
}

/* Overload */
- drawSelf:(NXRect *)r :(int) count
{
	int i;

	PSsetgray(NX_LTGRAY);
	PSrectfill(0.0, 0.0, bounds.size.width, bounds.size.height);
	PSsetgray(NX_WHITE);
	PSnewpath();
	PSmoveto(xc + x[0], yc + y[0]);
	for (i = 1; i < 4; i++)
		PSlineto(xc + x[i], yc + y[i]);
	PSfill();
	PSsetgray(NX_DKGRAY);
	PSnewpath();
	PSmoveto(xc + x[0], yc + y[0]);
	PSlineto(xc + x[1], yc + y[1]);
	PSlineto(xc + (x[2] + x[3])/2.0, yc + (y[2] + y[3])/2.0);
	PSfill();
	return self;
}

- drawIt: sender
{
	int angle;

	if (sender == nil) /* initialize */
		angle = 0;
	else
		angle = [angleSlider intValue];
	[angleText setIntValue: angle];
	if (angle == 0) {
		x[0] = x[3] = x0;
		x[1] = x[2] = x1;
		y[0] = y[1] = y0;
		y[2] = y[3] = y1;
	}else {
		double si = sin((double)angle * 3.14159265 / 180.0);
		double co = cos((double)angle * 3.14159265 / 180.0);
		double xw, xs, yw;
		x[0] = (xs = x0 * co) - (yw = y0 * si);
		x[1] = (xw = x1 * co) - yw;
		x[2] = xw - (yw = y1 * si);
		x[3] = xs - yw;
		y[0] = (xs = x0 * si) + (yw = y0 * co);
		y[1] = (xw = x1 * si) + yw;
		y[2] = xw + (yw = y1 * co);
		y[3] = xs + yw;
	}
	return [self display];
}

- writenAngle: sender
{
	int angle = [angleText intValue];

	while (angle < 0) angle += 360;
	while (angle >= 360) angle -= 360;
	[angleSlider setIntValue:((angle > 180) ? (angle - 360) : angle)];
	[self drawIt: self];
	[imageOp rotateAngle: self];
	return self;
}

@end
