extends CanvasLayer

@onready var animation_player = $AnimationPlayer
@onready var color_rect: ColorRect = $ColorRect
var _scene
var mid_change = false
var mid_animation = false

@export var timeshift_animation_length = 1.0

var _door_id : int = -1
var _tween : Tween

#region Change Game Scene
func change_scene_to(scene : Utils.GAME_SCENES):
	if mid_change or mid_animation:
		return
	mid_change = true
	Globals.pause()
	_scene = scene
	
	if _tween:
		_tween.kill()
	if animation_player.is_playing():
		animation_player.stop()
	animation_player.play("change_scene")

func _new_scene():
	get_tree().call_deferred("change_scene_to_file", Utils.GAME_SCENE_PATHS[_scene])
	SignalBus.change_scene_to(_scene)
	mid_change = false
#endregion

#region Time Shift
func change_time():
	if mid_change or mid_animation:
		return
	mid_change = true
	Globals.pause()
	
	if _tween:
		_tween.kill()
	if animation_player.is_playing():
		animation_player.stop()
	animation_player.play("change_time")

func _animate_time_change():
	color_rect.color = Color(0.0, 0.86, 0.92)
	var animation_offset = Vector2(0, color_rect.get_viewport_rect().size.y)
	color_rect.position = animation_offset
	if _tween:
		_tween.kill()
	_tween = get_tree().create_tween()
	_tween.tween_property(color_rect, "position", Vector2(0,0), timeshift_animation_length*0.4)
	_tween.tween_property(color_rect, "position", -animation_offset, timeshift_animation_length*0.4)
	_tween.play()
	await _tween.step_finished
	_tween.pause()
	if is_inside_tree():
		await get_tree().create_timer(timeshift_animation_length*0.1).timeout
	_change_time()
	if is_inside_tree():
		await get_tree().create_timer(timeshift_animation_length*0.1).timeout
	_tween.play()
	await _tween.finished
	_tween.kill()
	animation_player.play("RESET")

func _change_time():
	SignalBus.unpause()
	Globals.unpause()
	mid_change = false
	SignalBus.change_time()
#endregion

#region Change Rooms
func change_room(door_id : int):
	if mid_change or mid_animation:
		return
	_door_id = door_id
	
	mid_change = true
	Globals.pause()
	
	if _tween:
		_tween.kill()
	if animation_player.is_playing():
		animation_player.stop()
	animation_player.play("change_room")

func _change_room():
	SignalBus.unpause()
	Globals.unpause()
	mid_change = false
	SignalBus.enter_door(_door_id)
	_door_id = -1
#endregion
