package dev.cf.recipe;

import dev.cf.Tones;

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

/**
 * Picking one from a list, and picking several — without building either by hand.
 *
 * <p>This recipe exists because the reference app on this framework wrote its own single-choice
 * sheet while {@link ListViewWindow} sat unused. Reading this one screen is cheaper than
 * rediscovering it.</p>
 */
public class R06Select extends Recipe
{
   private static final String[] OPCOES = { "Beverages", "Food", "Cleaning", "Hygiene", "Bakery",
      "Frozen", "Pet" };

   private Label escolha;

   public String title()
   {
      return "Choosing from a list";
   }

   public String note()
   {
      return "ListViewWindow does single and multi selection, with the title, the confirm and the"
         + " tap-to-choose already wired.";
   }

   public void build(Component body) throws Exception
   {
      escolha = label("nothing chosen yet", 1f, false, Styles.captionColor, Position.START);
      escolha.testTag("recipe.choice");

      Button um = Tones.action("Pick one");
      um.testTag("recipe.pick.one");
      um.onAction(c -> abrir(ListViewWindow.ItemType.SINGLE));

      Button varios = new Button("Pick several");
      varios.testTag("recipe.pick.many");
      varios.onAction(c -> abrir(ListViewWindow.ItemType.MULTIPLE));

      body.add(LAY_AUTO, outgap(um, 0, 0, 0, .6f));
      body.add(LAY_AUTO, outgap(varios, 0, 0, 0, 1f));
      body.add(LAY_AUTO, escolha);
   }

   private void abrir(ListViewWindow.ItemType tipo)
   {
      try
      {
         final ListViewWindow janela = new ListViewWindow("Segment", OPCOES, tipo);
         // SINGLE closes on the tap; MULTIPLE waits for the confirm. Both arrive here.
         janela.onConfirm(c ->
         {
            int[] idx = janela.getSelectedIndices();
            StringBuilder sb = new StringBuilder();
            for (int i : idx)
               sb.append(sb.length() == 0 ? "" : ", ")
                  .append(OPCOES[i]);
            escolha.setText(sb.length() == 0 ? "nothing chosen" : sb.toString());
            escolha.setValidLayout(false);
            Screen.repaint();
         });
         janela.show();
      }
      catch (Exception e)
      {
         dev.crossfly.util.Debug.handle(e);
      }
   }
}
