/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package logic;

import game.VisualMIDlet;

/**
 *
 * @author avk
 */
public class GameThread implements Runnable {

    /**
     * Whether or not the main thread would like this thread to stop.
     */
    static boolean myShouldStop;
    /** 
     * A handle back to the graphical components.
     */
    BricksGameCanvas myCanvas;
    /** 
     * A handle back to the midlet object.
     */
    VisualMIDlet myMidlet;
    /**
     * The System.time of the last screen refresh, used to regulate refresh speed.
     */
    private long myLastRefreshTime;
    /**
     * The minimum amount of time to wait between frames.
     */
    private static long MIN_WAIT = 100;

    public GameThread(BricksGameCanvas canvas, VisualMIDlet midlet) {
        myCanvas = canvas;
        myMidlet = midlet;
    }

    /**
     * stops the game.
     */
    public synchronized void requestStop() {
        myShouldStop = true;
        this.notify();
    }

    public void run() {
        try {
            myCanvas.init();
            myCanvas.start();
        } catch (Exception e) {
            myMidlet.errorMsg(e);
        }

        // flush any keystrokes that occurred before the game started
        myCanvas.flushKeys();
        // start game cycle
        myShouldStop = false;
        while (true) {
            if (myShouldStop) {
                break;
            }
            myLastRefreshTime = System.currentTimeMillis();
            myCanvas.checkKeys();
            myCanvas.updateScreen();
            // pause to make sure not more than 20 frames
            // per second are shown:
            synchronized (this) {
                try {
                    wait(getWaitTime());
                } catch (Exception e) {
                }
            }
        }

    }

    /**
     * Get the amount of time to wait between screen refreshes.
     * Normally we wait only a single millisecond just to give
     * the main thread a chance to update the keystroke info,
     * but this method ensures that the game will not attempt
     * to show more than 20 frames per second.
     */
    private long getWaitTime() {
        long retVal = 1;
        long difference = System.currentTimeMillis() - myLastRefreshTime;
        if (difference < MIN_WAIT) {
            retVal = MIN_WAIT - difference;
        }
        return (retVal);
    }
}
