/*
 * Copyright (c) 1995-1997 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Permission to use, copy, modify, and distribute this software
 * and its documentation for NON-COMMERCIAL purposes and without
 * fee is hereby granted provided that this copyright notice
 * appears in all copies. Please refer to the file "copyright.html"
 * for further important copyright and licensing information.
 *
 * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
 * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
 * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR
 * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
 * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
 */
package bingo.game;

import bingo.shared.*;

class GamesThread extends Thread {

    private RingMaster ringMaster;
    private boolean moreGames = true;

    GamesThread(RingMaster ringMaster) {
	super("Bingo GamesThread");
	this.ringMaster = ringMaster;
    }

    public void run() {
	long now, startGameAt;
	int timeRemaining;

	while (moreGames) {
	    ringMaster.waitForFirstPlayer();

	    now = System.currentTimeMillis();
	    startGameAt = now + ringMaster.getGameParameters().getCountDown();

	    while (ringMaster.isCountingDown()) {
	        timeRemaining = (int)(Math.ceil((double)(startGameAt - now)/Constants.ONE_SECOND));
	        ringMaster.sendTimeRemainingMessage(timeRemaining);

	        try {
	            Thread.currentThread().sleep(Constants.FIVE_SECONDS);
	        } catch (InterruptedException e) {
	        }

	        now = System.currentTimeMillis();
	        if (now > startGameAt) {
 		    ringMaster.startGame();
		}
	    }
            new BallAnnouncer(ringMaster).start();

	    ringMaster.waitForGameToEnd();
	}
    }

    void noMoreGames() {
	moreGames = false;
    }
}
