// ============================================================================
// 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.*;
import de.caff.util.Tools;

import java.awt.*;

/**
 */
class SuicidePlayer
        implements FrameListener,
                   GameData
{
  private Communication com;

  SuicidePlayer(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)
  {
    SpaceShip ship = frame.getSpaceShip();
    if (ship != null) {
      if (frame.getAsteroidCount() < 10) {
        if (frame.getIndex() % 2 == 0) {
          com.pushButton(BUTTON_HYPERSPACE);
        }
        return;
      }
      int minDist2 = Integer.MAX_VALUE;
      Asteroid nearest = null;
      for (Asteroid ast: frame.getAsteroids()) {
        Point delta = ship.getDelta(ast);
        int dist2 = delta.x*delta.x + delta.y*delta.y;
        if (dist2 < minDist2) {
          minDist2 = dist2;
          nearest = ast;
        }
      }
      if (nearest != null) {
        double cross = Tools.crossProduct(ship.getDelta(nearest), ship.getDirection());
        if (cross <= 0) {
          com.pushButton(BUTTON_LEFT);
        }
        else {
          com.pushButton(BUTTON_RIGHT);
        }
        com.pushButton(BUTTON_THRUST);
      }
    }
  }
}
