package ocelot.desktop.node

import ocelot.desktop.color.RGBAColor
import ocelot.desktop.graphics.{Graphics, IconSource}
import ocelot.desktop.ui.event.ClickEvent
import ocelot.desktop.ui.widget.InputDialog
import ocelot.desktop.ui.widget.contextmenu.{ContextMenu, ContextMenuEntry}
import ocelot.desktop.util.DrawUtils
import totoro.ocelot.brain.nbt.NBTTagCompound

trait LabeledNode extends Node {
  private var _label: Option[String] = None

  def label: Option[String] = _label

  override def load(nbt: NBTTagCompound): Unit = {
    super.load(nbt)

    _label = Some(nbt.getString("label")).filter(_.nonEmpty)
  }

  override def save(nbt: NBTTagCompound): Unit = {
    super.save(nbt)

    nbt.setString("label", _label.getOrElse(""))
  }

  override def setupContextMenu(menu: ContextMenu, event: ClickEvent): Unit = {
    menu.addEntry(ContextMenuEntry("Set label", IconSource.Icons.Label) {
      new InputDialog(
        "Set label",
        text => {
          _label = Option.unless(text.isEmpty)(text)
        },
        _label.getOrElse(""),
      ).show()
    })

    super.setupContextMenu(menu, event)
  }

  override def drawLabel(g: Graphics): Unit = {
    super.drawLabel(g)

    for (label <- label) {
      g.setSmallFont()
      g.background = RGBAColor(0, 0, 0, 0)
      g.foreground = RGBAColor(150, 150, 150)
      DrawUtils.borderedText(g, position.x + 2, position.y - 10, label.take(8))
      g.setNormalFont()
    }
  }
}
