package ocelot.desktop.ui.widget

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

import java.util.UUID

class TunnelDialog(
  onConfirmed: String => Unit,
  initialText: String = "",
  inputValidator: String => Boolean = _ => true,
) extends ModalDialog {
  private val input = new TextInput(initialText) {
    focus()
    override def minimumSize: Size2D = Size2D(350, 24)
    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("Set channel name/code"), Padding2D(bottom = 8))

      children :+= new Widget {
        children :+= input
        children :+= new PaddingBox(
          new IconButton(
            IconSource.Icons.ButtonRandomize,
            IconSource.Icons.ButtonRandomize,
            drawBackground = true,
            releasedColor = ColorScheme("ButtonForeground"),
            padding = 3.5f,
            tooltip = Some("Generate random channel name"),
          ) {
            override def onClicked(): Unit = input.text = UUID.randomUUID().toString
          },
          new Padding2D(left = 8, right = 8),
        )
        children :+= new IconButton(
          IconSource.Icons.ButtonClipboard,
          IconSource.Icons.ButtonCheck,
          drawBackground = true,
          releasedColor = ColorScheme("ButtonForeground"),
          pressedColor = ColorScheme("ButtonConfirm"),
          padding = 3.5f,
          tooltip = Some("Copy channel name to the clipboard"),
        ) {
          override def onClicked(): Unit = UiHandler.clipboard = input.text
        }
      }

      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),
  )
}
