// ============================================================================
// File:               $File$
//
// Project:            
//
// Purpose:            
//
// Author:             Rammi
//
// Copyright Notice:   (c) 2008  Rammi (rammi@caff.de)
//
// Latest change:      $Date$
//
// History:	       $Log$
//=============================================================================
package de.caff.asteroid.rammi;

import de.caff.asteroid.*;

/**
 *  Call explicite garbage collection in pauses between levels.
 */
public class LevelPauseGarbageCollector
  implements FrameListener,
             GameData
{
  /** Have there been enemies in the last frame. */
  private boolean hadAsteroids = false;
  /** The count down (ufos may appear after asteroids are vanished). */
  private int countDown = 0;
  /** The communication object. */
  private final Communication com;

  public LevelPauseGarbageCollector(Communication com)
  {
    this.com = com;
  }

  /**
   * 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()) {
      boolean haveAsteroids = frame.getAsteroidCount() > 0;
      if (!haveAsteroids) {
        if (hadAsteroids) {
          countDown = 30;
        }
        else if (countDown > 0) {
          if (com.getButtons() == NO_BUTTON) {
            if (--countDown == 0) {
              if (frame.getUfo() == null  &&  frame.getBulletCount() == 0) {
                System.gc();
              }
            }
          }
        }
      }
      hadAsteroids = haveAsteroids;
    }
    else {
      hadAsteroids = false;
    }
  }
}
