
#import "AbstractTimerView.h"
#import "ErgoApp.h"
#import <appkit/Font.h>
#import <appkit/Text.h>
#import <appkit/TextField.h>

@implementation AbstractTimerView

- gameOver {
    gameOver = YES;
    return self;
}

- (BOOL) isWhite {
    return [self subclassResponsibility: _cmd], NO;
}

- startOfNewMove {
    if (!gameOver && [NXApp isWhiteMove] == [self isWhite]) {
	if (wasCounting) {
	    [timerTextField setIntValue: --timeLeft];
	    [self display];
	} else
	    wasCounting = YES;
	if (timeLeft)
	    [self perform: @selector(startOfNewMove) with: nil afterDelay: 1000
							  cancelPrevious: YES];
	else
	    [NXApp gameOverDueTo: TIMER_RAN_OUT winner: [NXApp isWhiteMove] ?
						      BLACK_WINS : WHITE_WINS];
    } else
	wasCounting = NO;
    return self;
}

/* Private methods: */

- appDidInit {
    return [self startOfNewMove];
}

#define	INITIAL_TIME  120
#define	FONT_FACTOR   0.7

- initFrame: (const NXRect *) frameRect {
    NXRect  localRect = *frameRect;
    double  fontSize = FONT_FACTOR * frameRect->size.height;

    [super initFrame: frameRect];
    gameOver = wasCounting = NO;
    localRect.origin.x = localRect.origin.y = 0;
    timerTextField = [[TextField alloc] initFrame: &localRect];
    [timerTextField setFont: [Font newFont: "Helvetica-Bold" size: fontSize]];
    [[timerTextField setSelectable: NO] setAlignment: NX_CENTERED];
    [timerTextField setBackgroundGray: [self isWhite] ? NX_WHITE : NX_BLACK];
    [timerTextField setTextGray: [self isWhite] ? NX_DKGRAY : NX_LTGRAY];
    [self addSubview: [timerTextField setIntValue: (timeLeft = INITIAL_TIME)]];
    return self;
}

@end
