#import "SpotView.h"
#import "Spot.h"
#import "Thinker.h"

@implementation SpotView

- (BOOL) acceptsFirstMouse
{ return YES;
}

- initFrame:(const NXRect *)r
{
[super initFrame:r];
[self allocateGState]; // For faster lock/unlockFocus
return self;
}

- lateInit
{
server = [myThinker server];
return self;
}

- mouseDown:(NXEvent *)theEvent
{
NXPoint mouseLocation, offset;
id spotToMove = nil;
int looping = YES, oldMask;

oldMask = [window addToEventMask:NX_MOUSEDRAGGEDMASK];
do {
mouseLocation = theEvent->location;
[self convertPoint:&mouseLocation fromView:nil];

switch (theEvent->type)
{
case NX_MOUSEDOWN:
spotToMove = [server getSpotForPoint:mouseLocation
spotLocation:&offset];
if (!spotToMove)
{
looping = NO;
break;
}
offset.x = mouseLocation.x - offset.x;
offset.y = mouseLocation.y - offset.y;
break;

case NX_MOUSEUP:
looping = NO;
// now fall into mousedragged implementation

case NX_MOUSEDRAGGED:
mouseLocation.x -= offset.x;
mouseLocation.y -= offset.E'1 if (![spotToMove setLocation:mouseLocation])
{
looping = NO;
spotToMove = nil;
}
break;
}

} while (looping && (theEvent = [NXApp getNextEvent:
NX_MOUSEUPMASK|NX_MOUSEDRAGGEDMASK]));

[window setEventMask:oldMask];

[spotToMove unlock];
// if (![myThinker isServer])
if ([spotToMove isProxy])
{
// this actually frees the local proxy but may or may not
// free the ref-counted spot on the server side

[spotToMove free];
}

return self;
}

- drawSelf:(const NXRect *) rects :(int)rectCount
{
int i, n;
id aSpot;
NXPoint pnt;

PSsetgray(NX_WHITE);
NXRectFill(&bounds);

// the list is retrieved bycopy so it is local, as are
// all the objects in the list

spotList = [myThinker spotList];

n = [spotList count];

for (i = 0; i < n; i++)
{
aSpot = [spotList objectAt:i];
NXSetColor([aSpot color]);
pnt = [aSpot location];
PSarc(pnt.x+15, pnt.y+15, 15, 0, 360);
PSfill();
}
return self;
}

@end