package ocelot.desktop.ui.widget

import ocelot.desktop.audio.{ClickSoundSourceFactory, SoundSource}
import ocelot.desktop.geometry.Padding2D
import ocelot.desktop.ui.layout.LinearLayout
import ocelot.desktop.ui.widget.modal.ModalDialog
import ocelot.desktop.util.Orientation

class InputDialog(
  title: String,
  onConfirmed: String => Unit,
  initialText: String = "",
  inputValidator: String => Boolean = _ => true,
) extends ModalDialog {
  private val input = new TextInput(initialText) {
    focus()

    override def validator(text: String): Boolean = inputValidator(text)

    override def onConfirm(): Unit = confirm()
  }

  private def confirm(): Unit = {
    onConfirmed(input.text)

    close()
  }

  children :+= new PaddingBox(
    new Widget {
      override val layout = new LinearLayout(this, orientation = Orientation.Vertical, gap = 8)

      children :+= new PaddingBox(
        new Label {
          override def text: String = title
        },
        Padding2D(bottom = 8),
      )

      children :+= input

      children :+= new Widget {
        children :+= new Filler
        children :+= new Button {
          override def text: String = "Cancel"
          override protected def clickSoundSource: ClickSoundSourceFactory = SoundSource.InterfaceClickLow
          override def onClick(): Unit = close()
        }
        children :+= new PaddingBox(
          new Button {
            override def text: String = "Ok"
            override def onClick(): Unit = {
              if (input.isInputValid)
                confirm()
            }
          },
          Padding2D(left = 8),
        )
      }
    },
    Padding2D.equal(16),
  )
}
