package ocelot.desktop.node

import ocelot.desktop.OcelotDesktop
import ocelot.desktop.graphics.IconSource
import ocelot.desktop.ui.UiHandler
import ocelot.desktop.ui.event.ClickEvent
import ocelot.desktop.ui.widget.contextmenu.{ContextMenu, ContextMenuEntry}
import totoro.ocelot.brain.entity.traits.{Entity, Environment, SidedEnvironment}
import totoro.ocelot.brain.nbt.NBTTagCompound
import totoro.ocelot.brain.network
import totoro.ocelot.brain.util.Direction

abstract class EntityNode(val entity: Entity with Environment) extends Node {
  if (!OcelotDesktop.workspace.getEntitiesIter.contains(entity)) {
    OcelotDesktop.workspace.add(entity)
  }

  def exposeAddress: Boolean = true

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

    val address = entity match {
      case env: SidedEnvironment =>
        env.sidedNode(Direction.South).address

      case _ => if (entity.node == null) null else entity.node.address
    }

    if (address != null && address.nonEmpty) {
      nbt.setString("address", address)
    }
  }

  override def setupContextMenu(menu: ContextMenu, event: ClickEvent): Unit = {
    if (exposeAddress && entity.node != null && entity.node.address != null) {
      menu.addEntry(
        ContextMenuEntry("Copy address", IconSource.Icons.Copy) {
          UiHandler.clipboard = entity.node.address
        }
      )
    }

    super.setupContextMenu(menu, event)
  }

  override def ports: Array[NodePort] = Array(NodePort())

  override def getNodeByPort(port: NodePort): network.Node = entity.node

  override def shouldReceiveEventsFor(address: String): Boolean =
    super.shouldReceiveEventsFor(address) || entity.node != null && address == entity.node.address

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

    OcelotDesktop.workspace.remove(entity)
  }
}
