!7

module ShowRandomColor > DynModule {
  RGB color;
  S myGuess, yourName;
  bool talk = true;
  
  transient JPanel colorPanel;
  transient JTextField tfYourName;
  transient JButton btnSave;
  
  visualize {
    if (color == null) setField(color := makeRandomColor());
    JComponent theForm = withRightMargin(makeForm2(
      "I call this color:", dm_fieldLabel('myGuess),
      "How do you call this color?", centerAndEastWithMargin(
        onEnter(tfYourName = selectAllOnFocus(dm_feedTopInputToTextField(dm_fieldTextField('yourName))), rThread saveName),
        btnSave = jbutton("Save", rThread saveName))));

    ret withRightAlignedButtons(
      centerAndSouthWithMargin(
        northAndCenterWithMargins(
          rightAlignedLine(
            jLiveValueLabel(mapLiveValue(func(O color) -> S { "Color Code: #" + color }, S, dm_fieldLiveValue('color))),
            jPopDownButton_noText("Choose color...", rThread chooseColor)),
          jSection("THE COLOR", colorPanel = singleColorPanel(toColor(color)))),
      jPreferredSizeToMinSizePlusY(5, theForm)),
      "New Color", rThread newColor);
  }
  
  void newColor enter {
    setColor(makeRandomColor());
  }
  
  void setColor(RGB color) enter {
    setField(+color);
    setField(myGuess := or((S) dm_callModule(dm_colorNamesModule(), 'getClosestColorName, color.getColor()), "no idea"));
    setField(yourName := myGuess);
    changeSingleColorPanel(colorPanel, color.getColor());
    selectAll(tfYourName);
  }
  
  void saveName enter {
    setField(yourName := trim(yourName));
    if (empty(yourName)) ret;
    if (eqic(myGuess, yourName))
      dm_infoBoxOrTalk(talk, randomLL(
        "Got this one right!",
        "I'm good!",
        "I'm so smart.",
        "Yay!"));
    else
      dm_infoBoxOrTalk(talk, quote(yourName) + (talk ? "," : "...") + " I see.");
    dm_callModule(dm_colorNamesModule(), 'addColorName, color.getColor(), yourName, "");
    newColor();
  }
  
  RGB makeRandomColor() {
    ret randomHSBColor();
  }
  
  void chooseColor enter {
    inputText("Choose a color (RRGGBB)", color.getHexString(), voidfunc(S s) enter {
      setColor(rgbFromHex(s))
    });
  }
  
  S switchableFields() { ret 'talk; }
}