extends Node

var CURRENT_LEVEL: Node3D = null
var CURRENT_PLAYER: CharacterBody3D = null
var combined_signal : Observable

func _ready() -> void:
  var lvl: Resource = load("res://assets/levels/maps/debug1.tscn")
  var player: Resource = load("res://assets/characters/coco/coco.tscn")
  CURRENT_LEVEL = lvl.instantiate()
  CURRENT_PLAYER = player.instantiate()
  CURRENT_PLAYER.transform.origin = Vector3(0, 1, 0)
  add_child(CURRENT_LEVEL)
  CURRENT_LEVEL.add_child(CURRENT_PLAYER)
  combined_signal = GDRx.from_signal(Messagebus.CHANGE_SCENE)\
    .debounce(0.2)
  combined_signal.subscribe(transition_to).dispose_with(self)

func transition_to(scene: String):
  print(">>>>>>>"+str(scene))
  CURRENT_LEVEL.remove_child(CURRENT_PLAYER)
  remove_child(CURRENT_LEVEL)
  var lvl = load("res://assets/levels/maps/"+scene+".tscn")
  var new_level = lvl.instantiate()
  new_level.add_child(CURRENT_PLAYER)
  CURRENT_PLAYER.transform.origin = Vector3(0, 1, 0)
  CURRENT_PLAYER.set_owner(new_level)
  add_child(new_level)
  print("Transitioned to "+str(scene))
  CURRENT_LEVEL = new_level

func _process(delta: float) -> void:
  if (CURRENT_PLAYER.global_position.y) < -5:
    CURRENT_PLAYER.translate(Vector3.UP*10)
    # TODO: blah blah
    
