package wow.doge.mygame.state

import com.jme3.app.Application
import com.jme3.app.SimpleApplication
import com.jme3.app.state.AppState
import com.jme3.scene.Node
import com.jme3.app.state.BaseAppState
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

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

  protected def getOrCreateNode(parent: Node, id: String) =
    Option(parent.getChild(id)).fold {
      val node = new Node(id)
      parent.attachChild(node)
      node
    }(node => node.asInstanceOf[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)
    }
  }

}
