package ocelot.desktop.ui.widget

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

class ScreenAspectRatioDialog(screenNode: ScreenNode) extends ModalDialog {
  children :+= new PaddingBox(
    new Widget {
      override val layout = new LinearLayout(this, orientation = Orientation.Vertical)

      children :+= new PaddingBox(new Label("Set aspect ratio"), Padding2D(bottom = 16))

      private var typedWidth: Option[Int] = Some(screenNode.screen.aspectRatio._1.toInt)
      private var typedHeight: Option[Int] = Some(screenNode.screen.aspectRatio._2.toInt)
      private def canConfirm: Boolean = typedWidth.isDefined && typedHeight.isDefined

      private def confirm(): Unit = {
        screenNode.screen.aspectRatio = (
          typedWidth.get.toDouble,
          typedHeight.get.toDouble,
        )

        close()
      }

      def addInput(maxValue: Int, valueGetter: () => Option[Int], valueSetter: Option[Int] => Unit): Unit = {
        children :+= new PaddingBox(
          new TextInput(valueGetter().getOrElse(1).toString) {
            override def onInput(text: String): Unit = {
              var result: Option[Int] = None

              try {
                val intValue = text.toInt

                if (intValue >= 1 && intValue <= maxValue)
                  result = Some(intValue)
              } catch {
                case _: NumberFormatException =>
              }

              valueSetter(result)
            }

            override def validator(text: String): Boolean = valueGetter().isDefined

            override def onConfirm(): Unit =
              if (canConfirm)
                confirm()
          },
          Padding2D(bottom = 8),
        )
      }

      children :+= new Label("Width:")

      addInput(
        8,
        () => typedWidth,
        value => typedWidth = value,
      )

      children :+= new Label("Height:")

      addInput(
        6,
        () => typedHeight,
        value => typedHeight = value,
      )

      children :+= new Widget {
        children :+= new Filler

        children :+= new PaddingBox(
          new Button {
            override def text: String = "Cancel"
            override protected def clickSoundSource: ClickSoundSourceFactory = SoundSource.InterfaceClickLow
            override def onClick(): Unit = close()
          },
          Padding2D(right = 8),
        )

        val confirmButton: Button = new Button {
          override def text: String = "Apply"
          override def onClick(): Unit = confirm()
          override def enabled: Boolean = canConfirm
        }

        children :+= confirmButton
      }
    },
    Padding2D.equal(16),
  )
}
