package dev.cf.recipe;

import dev.cf.Tones;

import dev.crossfly.test.*;
import dev.crossfly.ui.*;
import dev.crossfly.ui.color.*;
import dev.crossfly.ui.graphics.*;
import dev.crossfly.ui.layout.*;
import dev.crossfly.ui.style.*;

import static dev.crossfly.ui.Widgets.*;

/**
 * Making a screen verifiable: tag what a test will point at, then read the tree back.
 *
 * <p>The button below prints this screen's structural portrait to the log — the same text a test
 * compares against a committed baseline. Seeing it once is usually enough to understand why the
 * portrait catches what assertions never think to ask.</p>
 */
public class R09Testable extends Recipe
{
   private int toques;
   private Label contador;

   public String title()
   {
      return "Making a screen testable";
   }

   public String note()
   {
      return "Tag anything a test must reach. Text breaks on rewording, class breaks on a second"
         + " instance, index breaks on insertion — a tag breaks only when someone removes it.";
   }

   public void build(Component body) throws Exception
   {
      contador = label(texto(), 2f, true, Tones.accent(), Position.START);
      contador.testTag("demo.counter");

      Button somar = Tones.action("Add one");
      somar.testTag("demo.add");
      somar.onAction(c ->
      {
         toques++;
         contador.setText(texto());
         contador.setValidLayout(false);
         Screen.repaint();
      });

      Button dump = new Button("Print the tree");
      dump.testTag("demo.dump");
      dump.onAction(c -> dev.crossfly.util.Debug.log(ScreenReport.tree(this, title())));

      body.add(LAY_AUTO, outgap(contador, 0, 0, 0, .8f));
      body.add(LAY_AUTO, outgap(somar, 0, 0, 0, .6f));
      body.add(LAY_AUTO, outgap(dump, 0, 0, 0, 1f));

      // The three lines are code, so they get a surface of their own rather than sitting loose
      // in the page looking like more prose.
      Card codigo = Tones.card(Tones.support());
      codigo.add(LAY_AUTO, Tones.head(0xE86F, "From a TestCase, that is", Tones.support()));
      for (String l : new String[] { "clickTag(\"demo.add\");",
         "verifyTag(\"demo.counter\").text(\"1 tap\");",
         "new ScreenReport(this).checkBaseline(dir, \"demo\", false);" })
         codigo.add(LAY_AUTO, outgap(label(l, 1f, false, Styles.textColor, Position.START),
            0, 0, 0, .25f));
      body.add(LAY_AUTO, codigo);
   }

   private String texto()
   {
      return toques + (toques == 1 ? " tap" : " taps");
   }
}
