package ocelot.desktop.ui.widget.card

import ocelot.desktop.geometry.{Padding2D, Size2D}
import ocelot.desktop.inventory.item.OcelotCardItem
import ocelot.desktop.ui.layout.{AlignItems, Layout, LinearLayout}
import ocelot.desktop.ui.widget.{Button, Checkbox, Filler, Label, LogWidget, PaddingBox, TextInput, Widget}
import ocelot.desktop.ui.widget.window.PanelWindow
import ocelot.desktop.util.Orientation

class OcelotCardWindow(item: OcelotCardItem) extends PanelWindow {
  override protected def title: String = s"Ocelot card ${item.component.node.address}"

  private val logWidget: LogWidget = new LogWidget {
    override protected def messages: Iterable[String] = item.messages
    override protected def textWidth: Int = 50

    override def minimumSize: Size2D = super.minimumSize.copy(height = 300)
    override def maximumSize: Size2D = minimumSize
  }

  setInner(new Widget {
    override protected val layout: Layout = new LinearLayout(this, orientation = Orientation.Vertical, gap = 4f)

    children :+= logWidget

    children :+= new Label {
      override def text: String = s"Messages: ${item.messages.length} / ${item.messageLimit}"
    }

    children :+= new Widget {
      override protected val layout: Layout =
        new LinearLayout(this, orientation = Orientation.Horizontal, alignItems = AlignItems.Center)

      children :+= new PaddingBox(
        new Label {
          override def text: String = "Limit"

          override def maximumSize: Size2D = minimumSize
        },
        Padding2D(right = 12)
      )

      children :+= new TextInput(item.messageLimit.toString) {
        private def parseInput(text: String): Option[Int] = text.toIntOption.filter(_ > 0)

        override def minimumSize: Size2D = super.minimumSize.copy(width = 60)

        override def maximumSize: Size2D = minimumSize

        override def validator(text: String): Boolean = parseInput(text).nonEmpty

        override def onConfirm(): Unit = {
          for (messageLimit <- parseInput(text)) {
            item.messageLimit = messageLimit
          }

          super.onConfirm()
        }
      }

      children :+= new Filler

      children :+= new Checkbox("Scroll to end") {
        override def checked: Boolean = logWidget.scrollToEnd

        override def checked_=(value: Boolean): Unit = {
          logWidget.scrollToEnd = value
        }
      }

      children :+= new Button {
        override def text: String = "Clear"
        override def onClick(): Unit = clear()
      }
    }
  })

  private def clear(): Unit = {
    item.clear()
  }

  def onMessagesAdded(count: Int): Unit = {
    logWidget.onMessagesAdded(count)
  }

  def onMessagesRemoved(count: Int): Unit = {
    logWidget.onMessagesRemoved(count)
  }
}
