class_name RootScene extends Node3D

@export var overworld:Node3D = null
@export var initial:Node3D = null
@export var battle:Node3D = null
@export var cooking:Node3D = null
@export var currentScene:Node = null

func _enter_tree() -> void:
  SCENE.sceneChanged.connect(onSceneChange)
  SCENE.setScene(SceneSingleton.SceneType.INITIAL)

func _exit_tree() -> void:
  push_error("RootScene should not be removed from the scene tree. This is a bug.")

func removeAndHide(node:Node3D) -> void:
  if node && node.get_parent():
    node.get_parent().remove_child(node)
  node.visible = false

func addAndShow(node:Node3D) -> void:
  if node && currentScene:
    if node.get_parent() && node.get_parent() != currentScene:
      node.get_parent().remove_child(node)
    currentScene.add_child(node)
  node.visible = true

func onSceneChange(newScene:SceneSingleton.SceneType) -> void:
  match newScene:
    SceneSingleton.SceneType.INITIAL:
      removeAndHide(overworld)
      removeAndHide(battle)
      removeAndHide(cooking)
      addAndShow(initial)

    SceneSingleton.SceneType.OVERWORLD:
      removeAndHide(initial)
      removeAndHide(battle)
      removeAndHide(cooking)
      addAndShow(overworld)

    SceneSingleton.SceneType.BATTLE:
      removeAndHide(initial)
      removeAndHide(overworld)
      removeAndHide(cooking)
      addAndShow(battle)

    SceneSingleton.SceneType.COOKING:
      removeAndHide(initial)
      removeAndHide(overworld)
      removeAndHide(battle)
      addAndShow(cooking)

    _:
      removeAndHide(initial)
      removeAndHide(overworld)
      removeAndHide(battle)
      removeAndHide(cooking)
