// ============================================================================
// File:               $File$
//
// Project:            
//
// Purpose:            
//
// Author:             Rammi
//
// Copyright Notice:   (c) 2008  Rammi (rammi@caff.de)
//                     This code is in the public domain.
//                     Use at own risk.
//                     No guarantees given.
//
// Latest change:      $Date$
//
// History:	       $Log$
//=============================================================================
package de.caff.asteroid;

/**
 *  Print out the score a given number of frames after the ship appeared the first time.
 *
 *  This class is part of a solution for a
 *  <a href="http://www.heise.de/ct/creativ/08/02/details/">competition by the German computer magazine c't</a>
 */
public class TimedScorePrinter
        implements FrameListener,
                   GameData
{
  /** The default number of frames. */
  public static final int DEFAULT_FRAMES = 5*60*FRAMES_PER_SECOND;
  /** Frame to print while unknown. */
  public static final int NO_FRAME = -1;
  /** Number of frame when counting starts (-1: yet unknown). */
  private int startFrame = -1;
  /** The numbers of frames to count until printing. */
  private final int countFrames;
  /** The last score printed. */
  private int score = 0;

  /**
   *  Default constructor.
   */
  public TimedScorePrinter()
  {
    this(DEFAULT_FRAMES);
  }

  /**
   *  Constructors.
   *  @param frames frames to count before score is printed
   */
  public TimedScorePrinter(int frames)
  {
    countFrames = frames;
  }

  /**
   * Called each time a frame is received.
   * <p/>
   * <b>ATTENTION:</b> this is called from the communication thread!
   * Implementing classes must be aware of this and take care by synchronization or similar!
   *
   * @param frame the received frame
   */
  public void frameReceived(FrameInfo frame)
  {
    if (!frame.isGameRunning()) {
      startFrame = -1;
    }
    else if (startFrame == -1) {
      if (frame.getSpaceShip() != null) {
        startFrame = frame.getIndex();
      }
    }
    else if ((frame.getIndex() - startFrame) % countFrames == 0) {
      score = frame.getScore();
      int frames = frame.getIndex() - startFrame;
      int seconds = frames/FRAMES_PER_SECOND;
      System.out.println(String.format("Score after %5d frames (%02d:%02d):\t%d", frames, seconds/60, seconds % 60, score));
    }
  }

  /**
   *  Get the last score counted.
   *  @return last counted score (<code>0</code> if not counted yet)
   */
  public int getLatestScore()
  {
    return score;
  }
}
