package ocelot.desktop.inventory.traits

import ocelot.desktop.OcelotDesktop
import ocelot.desktop.inventory.Item
import totoro.ocelot.brain.entity.traits.{Entity, WorkspaceAware}

/** Implemented by [[Item]]s that wrap an [[Entity]].
  *
  * @note Subclasses must provide a unary constructor that accepts the [[entity]].
  */
trait EntityItem extends Item with PersistableItem {
  /** The entity wrapped by this item.
    *
    * @note The value must already be available during the trait's initialization.
    */
  def entity: Entity

  private def setWorkspace(): Unit = entity match {
    case entity: WorkspaceAware => entity.workspace = OcelotDesktop.workspace
    case _ =>
  }

  override def reinserting(f: => Unit): Unit = super.reinserting {
    // removal may have set the workspace to null
    setWorkspace()

    f

    // since we have absolutely no idea what f does, workspace could've been set to null again
    setWorkspace()
  }

  setWorkspace()

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

    // this one isn't strictly necessary, I believe, but I'll keep this for the sake of symmetry and safety
    setWorkspace()
  }

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

    // fix up ComponentInventory's zeroing out the workspace
    setWorkspace()
  }
}
