package org.intentor.yabai.states;

import javax.microedition.lcdui.Graphics;
import lejos.nxt.Button;
import lejos.nxt.LCD;
import lejos.nxt.Sound;
import lejos.util.Timer;
import lejos.util.TimerListener;
import org.intentor.yabai.constants.Asset;
import org.intentor.yabai.constants.StateName;
import org.intentor.yabai.controllers.RearTouchSumoController;
import org.intentor.yabai.core.IBotController;
import org.intentor.yabai.core.State;
import org.intentor.yabai.valueobjects.AiParameters;

/**
 * Runs the behaviours that executes the AI.
 */
public class RunningState extends State implements TimerListener {
	/** Timeout to wait for button press (milliseconds). */
	protected static final int BUTTON_POLL_INTERVAL = 10;
	
	/** AI parameters. */
	protected AiParameters parameters;
	/** Startup timer. */
	protected Timer timer;
	/** Timer counter. */
	protected int counter;
	/** The message to display. */
	protected String message = "";
	
	/**
	 * Creates a new instance of the class.
	 * 
	 * @param parameters AI parameters.
	 */
	public RunningState(AiParameters parameters) {
		this.parameters = parameters;
	}
	
	@Override
	public void onStart() {
		this.timer = new Timer(1000, this);
		this.counter = this.parameters.timer;
		this.message = "Starting... " + String.valueOf(this.counter);
		
		this.timer.start();
	}
	
	@Override
	public void update() {
		LCD.clear();		
		
		this.graphics.drawRegion(Asset.LOGO_IAB, 0, 0,
			Asset.LOGO_IAB.getWidth(), Asset.LOGO_IAB.getHeight(),
			0, LCD.SCREEN_WIDTH - Asset.LOGO_IAB.getWidth(), 0, Graphics.LEFT | Graphics.TOP);
		
		LCD.drawString(this.message, 0, 3);
		LCD.drawString("Press to stop", 0, LCD.DISPLAY_CHAR_DEPTH - 1);
		
		int button = Button.waitForAnyPress(BUTTON_POLL_INTERVAL);		
		if (button != 0) {
			this.timer.stop();
			this.stateManager.start(StateName.HOME);
		}
	}

	@Override
	public void timedOut() {
		this.counter--;
		Sound.playTone(500 + (this.parameters.timer - this.counter) * 50, (this.counter == 0 ? 500 : 100));
		
		if (this.counter == 0) {
			this.timer.stop();
			this.message = "";
			IBotController controller = new RearTouchSumoController(this.parameters);
			controller.start();
		} else {
			this.message = "Starting... " + String.valueOf(this.counter);
		}
	}
}
@@ -1301,18 +1301,35 @@
 unter);%0A
+%0A
 %09%09
+this.timedOut();
 %0A%09%09this.
@@ -1601,16 +1601,50 @@
 );%0A%09%09%0A%09%09
+if (this.message != null) %7B%0A%09%09    
 LCD.draw
@@ -1671,16 +1671,26 @@
  0, 3);%0A
+        %7D%0A
 %09%09LCD.dr
@@ -2135,18 +2135,20 @@
 ssage = 
-%22%22
+null
 ;%0A%09%09%09IBo
@@ -2294,32 +2294,33 @@
  String.valueOf(
+(
 this.counter);%0A%09
@@ -2315,16 +2315,21 @@
 .counter
+ + 1)
 );%0A%09%09%7D%0A%09

Fix start counter counting