package wow.doge.mygame.state

import com.jme3.app.Application
import com.jme3.app.SimpleApplication
import com.jme3.app.state.AppState
import com.jme3.app.state.BaseAppState
import com.jme3.scene.Node
import com.jme3.scene.Spatial
import com.simsilica.es.EntityData
import com.simsilica.es.base.DefaultEntityData

trait MyBaseState extends BaseAppState {

  var simpleApp: SimpleApplication = null
  implicit val entityData: EntityData = new DefaultEntityData()
  def stateManager = simpleApp.getStateManager
  def guiNode = simpleApp.getGuiNode
  def rootNode = simpleApp.getRootNode
  def assetManager = simpleApp.getAssetManager
  def inputManager = simpleApp.getInputManager
  def cam = simpleApp.getCamera

  override protected final def initialize(app: Application): Unit = {
    simpleApp = app.asInstanceOf[SimpleApplication]
    init()
    // stateManager.getState(classOf[FlyCamAppState]).getCamera().setMoveSpeed(100)
  }

  protected def init(): Unit
  protected def stop(): Unit

  override protected def cleanup(app: Application): Unit = {
    entityData.close()
    // stop()
  }

  protected def getChildOption(parent: Node, id: String) =
    Option(parent.getChild(id))

  protected def getOrCreateSpatial(parent: Node, id: String): Spatial =
    Option(parent.getChild(id)).getOrElse {
      val node: Spatial = new Node(id)
      parent.attachChild(node)
      node
    }

  protected def enableStates(classes: Class[_ <: AppState]*) =
    setEnabledToStates(true, classes: _*)
  protected def disableStates(classes: Class[_ <: AppState]*) =
    setEnabledToStates(false, classes: _*)

  protected def setEnabledToStates(
      enabled: Boolean,
      classes: Class[_ <: AppState]*
  ) = {
    for (clazz <- classes) {
      val st = stateManager.getState(clazz)
      if (st != null) st.setEnabled(enabled)
    }
  }

  protected def removeStates(classes: Class[_ <: AppState]*) = {
    for (clazz <- classes) {
      val st = stateManager.getState(clazz)
      if (st != null) stateManager.detach(st)
    }
  }

}
