// ============================================================================
// 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.*;

/**
 *  Start a player used for tests.
 */
public class TestPlayerStarter
  implements PlayerStarter,
             GameData
{
  private static class TestPlayer
          implements FrameListener
  {
    private static final int[] BUTTON_SEQUENCE = {
            NO_BUTTON,
            NO_BUTTON,
            NO_BUTTON,
            NO_BUTTON,
            NO_BUTTON,
            NO_BUTTON,
            NO_BUTTON,
            NO_BUTTON,
            NO_BUTTON,
            NO_BUTTON,
            NO_BUTTON,
            NO_BUTTON,
            NO_BUTTON,
            NO_BUTTON,
            NO_BUTTON,
            NO_BUTTON,
            BUTTON_LEFT,
            NO_BUTTON,
            NO_BUTTON,
            BUTTON_FIRE
    };
    private Communication com;
    private int prefix = 8;
    private int rotate;
    private int rotateKey;
    private boolean fire = false;

    private TestPlayer(Communication com)
    {
      this.com = com;
      if (System.getProperty("TestRotate") != null) {
        rotate = Integer.parseInt(System.getProperty("TestRotate"));
        if (rotate < 0) {
          rotate = -rotate;
          rotateKey = BUTTON_RIGHT;
        }
        else if (rotate == 0) {
          fire = true; 
        }
        else {
          rotateKey = BUTTON_LEFT;
        }
      }
    }

    /**
     * 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.getSpaceShip() != null) {
        if (prefix > 0) {
          --prefix;
        }
        else if (rotate-- > 0) {
          com.pushButton(rotateKey);
          if (rotate == 0) {
            prefix = 2;
            fire = true;
          }
        }
        else if (fire) {
          com.pushButton(BUTTON_FIRE);
          fire = false;
          prefix = 16;
        }
        else {
          System.exit(0);
        }
      }
    }
  }
  /**
   * Start the player.
   * It is assumed that this method returns after starting the player.
   *
   * @param com communication access
   */
  public void startPlayer(Communication com)
  {
    TestPlayer player = new TestPlayer(com);
    com.addFrameListener(player);
  }
}
