
#import "ScoreView.h"
#import "BlackFilledSquare.h"
#import "WhiteFilledSquare.h"
#import <appkit/Font.h>		/* for Font's newFont:size: message */
#import <appkit/Text.h>		/* to get NX_CENTERED definition */
#import <appkit/TextField.h>

@implementation ScoreView

#define MAX_NUM_PIECES  37     /* should really be calculated from the board */

- letOtherColorMove {
    short  winType;

    [self updateTextFields];
    winType = whiteCount == blackCount ? GAME_TIED :
	       whiteCount > blackCount ? WHITE_WINS : BLACK_WINS;
    if (blackCount + whiteCount == MAX_NUM_PIECES)
	[NXApp gameOverDueTo: BOARD_FILLED winner: winType];
    if (([NXApp isWhiteMove] || whiteCount) && blackCount)
	[NXApp allowOtherColorMove];
    else
	[NXApp gameOverDueTo: NO_OPPONENTS winner: winType];
    return self;
}

/* Private methods: */

- appDidInit {
    return [self updateTextFields];
}

- countSquareAsWhite: (BOOL) isWhite {
    isWhite ? ++whiteCount : ++blackCount;	/* may not be fully portable */
    return self;				   /* (but I like it...:-) */
}

- hitTest: (NXPoint *) aPoint {
    return nil;   /* ignore mouseDown: or subviews of us will try to respond */
}

#define	VERTICAL_ADJUST  (-0.23 * frameRect->size.height)    /* magic double */

- initFrame: (const NXRect *) frameRect {
    NXRect  blackRect = *frameRect, whiteRect = *frameRect;

    [super initFrame: frameRect];
    blackRect.size.width = (whiteRect.size.width /= 2);
    blackRect.origin.x = whiteRect.size.width; /* ^ makes 2 equal-size rects */
    blackRect.origin.y = whiteRect.origin.y = whiteRect.origin.x = 0;
    [self addSubview: [[BlackFilledSquare alloc] initFrame: &blackRect]];
    [self addSubview: [[WhiteFilledSquare alloc] initFrame: &whiteRect]];
    whiteRect.origin.y = blackRect.origin.y = VERTICAL_ADJUST;
    blackTextField = [self initTextFieldFrame: &blackRect];
    whiteTextField = [self initTextFieldFrame: &whiteRect];
    [self addSubview: [blackTextField setTextGray: NX_LTGRAY]];
    [self addSubview: [whiteTextField setTextGray: NX_DKGRAY]];
    return self;
}

#define	FONT_SIZE      14	/* picking Font's "design size" works best */
#define	CIRCLE_FACTOR  0.4	/* needed since text must fit inside circle */

- initTextFieldFrame: (const NXRect *) frameRect {
    id      aTextField = [[TextField alloc] initFrame: frameRect];
    double  scaleFactor = CIRCLE_FACTOR * frameRect->size.height / FONT_SIZE;

    [aTextField setFont: [Font newFont: "Times-Bold" size: FONT_SIZE]];
    [aTextField scale: scaleFactor : scaleFactor];
    [[aTextField setBackgroundTransparent: YES] setSelectable: NO];
    return [[aTextField setBezeled: NO] setAlignment: NX_CENTERED];
}

- updateTextFields {
    blackCount = whiteCount = 0;
    [NXApp makeSquaresPerform: @selector(calculateScore:) with: self];
    [blackTextField setIntValue: blackCount];
    [whiteTextField setIntValue: whiteCount];
    return [self display];
}

@end
