package org.geepawhill.contentment;

import javafx.animation.SequentialTransition;
import javafx.geometry.Bounds;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Text;

public class LabelBoxStep implements Step {

	private String text;
	private Text label;
	private Rectangle rectangle;
	private Bounds bounds;
	private final SequentialTransition transition;
	private final NodeKeeper keeper;

	public LabelBoxStep(String text, double xCenter, double yCenter) {
		keeper = new NodeKeeper();
		label = new Text(xCenter, yCenter, "");
		rectangle = new Rectangle();
		keeper.keep(label,rectangle);
		bounds = label.getBoundsInParent();
		this.text = text;
		transition = new SequentialTransition();
	}

	@Override
	public void after(Context context) {
		transition.stop();
		keeper.addTo(context.canvas);
		animateDrawText(1.0, context);
		animateComputeBox(1.0, context);
		animateDrawBox(1.0, context);
	}

	@Override
	public void before(Context context) {
		transition.stop();
		keeper.removeFrom(context.canvas);
	}

	@Override
	public void play(Context context) {
		// TODO Auto-generated method stub
		keeper.addTo(context.canvas);
		transition.getChildren().clear();
		transition.getChildren().add(new ContextTransition(context,500, this::animateDrawText));
		transition.getChildren().add(new ContextTransition(context,1, this::animateComputeBox));
		transition.getChildren().add(new ContextTransition(context,500, this::animateDrawBox));
		transition.setOnFinished(context.onFinished);
		transition.playFromStart();
	}

	@Override
	public void pause(Context context) {
		transition.pause();

	}

	@Override
	public void resume(Context context) {
		transition.play();
	}

	protected void animateDrawText(double frac, Context context)
	{
		String newText = text.substring(0, (int) (frac * text.length()));
		label.setText(newText);
	}

	protected void animateComputeBox(double frac, Context context)
	{
		bounds = label.getBoundsInParent();

		rectangle.setFill(Color.TRANSPARENT);
		rectangle.setStroke((Paint)context.styles.get(StyleId.LineColor).value);
		rectangle.setStrokeWidth((double)context.styles.get(StyleId.PenWidth).value);
		rectangle.setX(bounds.getMinX());
		rectangle.setY(bounds.getMinY());
		rectangle.setWidth(0d);
		rectangle.setHeight(0d);
	}

	protected void animateDrawBox(double frac, Context context)
	{
		rectangle.setWidth(bounds.getWidth() * frac);
		rectangle.setHeight(bounds.getHeight() * frac);
	}

}

@@ -2339,16 +2339,47 @@
 ht(0d);%0A
+%09%09rectangle.setVisible(false);%0A
 %09%7D%0A%0A%09pro
@@ -2536,14 +2536,57 @@
  frac);%0A
+%09%09if(frac!=0d) rectangle.setVisible(true);%0A
 %09%7D%0A%0A%7D%0A

Fix one-pixel rectangle bug. grrrrr.