package ocelot.desktop.node.nodes

import ocelot.desktop.OcelotDesktop
import ocelot.desktop.color.Color
import ocelot.desktop.entity.OpenFMRadio
import ocelot.desktop.graphics.{Graphics, IconSource}
import ocelot.desktop.node.{EntityNode, LabeledEntityNode, WindowedNode}
import ocelot.desktop.windows.OpenFMRadioWindow

class OpenFMRadioNode(val openFMRadio: OpenFMRadio)
    extends EntityNode(openFMRadio) with LabeledEntityNode with WindowedNode[OpenFMRadioWindow] {
  override def icon: IconSource = IconSource.Nodes.OpenFMRadio

  override def rotatable: Boolean = true

  private var lastTick = OcelotDesktop.ticker.tick
  private var animationIndex = 0
  private var _animatedText: Option[String] = None

  private def animatedText: String = {
    val tick = OcelotDesktop.ticker.tick

    if (_animatedText.isDefined && tick - lastTick < 10)
      return _animatedText.get

    var text = openFMRadio.screenText

    if (text.length > 6) {
      text += "      "

      if (animationIndex < text.length) {
        val first = text.substring(0, animationIndex + 1)
        val rest = text.substring(animationIndex + 1)

        text = rest + first

        animationIndex += 1
      } else {
        animationIndex = 0
      }

      text = text.substring(0, 7)
    }

    lastTick = tick
    _animatedText = Option(text)

    text
  }

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

    val text = animatedText
    val textWidth = text.map(g.font.charWidth(_)).sum
    val scale = 0.7f

    g.save()

    g.scale(scale)
    g.background = Color.Transparent
    g.foreground = openFMRadio.screenColor

    g.text(
      (position.x + size.width / 2) / scale - textWidth / 2,
      (position.y + 18) / scale,
      text,
    )

    g.restore()
    g.setNormalFont()
  }

  override def dispose(): Unit = {
    super.dispose()

    openFMRadio.stop()
  }

  override def createWindow(): OpenFMRadioWindow = new OpenFMRadioWindow(this)
}
