class_name Box
extends PuzzleElement

@onready var raycast: RayCast2D = $RayCast2D
@onready var animation_player: AnimationPlayer = $AnimationPlayer
@onready var audio_player: AudioStreamPlayer2D = $AudioStreamPlayer2D
@onready var manager: BoxPuzzle = $"../"
@onready var tile_map: MainLevel = get_tree().root.get_child(0).get_node("TileMap")

const TILE_SIZE = 8

var is_finished = false
var is_moving = false
var input_dir: Vector2

func _ready():
	pass

func _process(delta):
	pass
	
func _physics_process(delta):
	pass

func interact(player: Player):
	if !is_finished and !is_moving:
		input_dir = player.input_dir
		raycast.target_position = player.input_dir * 8
		raycast.force_raycast_update()

		if tile_map.is_death_tile(global_position + raycast.target_position):
			return

		var collider = raycast.get_collider()
		var is_switch = collider is BoxSwitch
		if raycast.is_colliding() and not is_switch:
			return
			
		is_moving = true
		audio_player.play()
		var tween = create_tween()
		tween.tween_property(self, "position", position + input_dir * TILE_SIZE, 0.45)
		tween.tween_callback(func(): 
			is_moving = false
			if is_switch:
				complete()
		)
		
	pass

func _check_completion():
	pass

func complete():
	if is_finished:
		return
		
	animation_player.play(&"complete")
	is_finished = true
