extends CharacterBody2D

const TILE_SIZE = 64
const MOVE_SPEED = 300

enum MaskType { NONE, TRIANGLE, CIRCLE, SQUARE }

var target_position: Vector2
var current_mask: MaskType = MaskType.NONE

@onready var sprite = $Sprite2D
@onready var mask_sprite = $MaskSprite

var PLAYER_TEXTURE = preload("res://assets/player/player.png")

var TRIANGLE_MASK = preload("res://assets/masks/triangle_mask.png")
var CIRCLE_MASK = preload("res://assets/masks/circle_mask.png")
var SQUARE_MASK = preload("res://assets/masks/square_mask.png")

func _ready():
	sprite.texture = PLAYER_TEXTURE
	fit_sprite_to_tile(sprite)

	target_position = position
	update_mask_visual()

func _physics_process(delta):
	if position != target_position:
		position = position.move_toward(target_position, MOVE_SPEED * delta)
		return

	var input_dir = Vector2.ZERO

	if Input.is_action_pressed("ui_up"):
		input_dir.y = -1
	elif Input.is_action_pressed("ui_down"):
		input_dir.y = 1
	elif Input.is_action_pressed("ui_left"):
		input_dir.x = -1
	elif Input.is_action_pressed("ui_right"):
		input_dir.x = 1

	if input_dir != Vector2.ZERO:
		attempt_move(input_dir)

func attempt_move(direction: Vector2):
	var map_node = get_parent().get_node("Map")

	var new_pos = position + direction * TILE_SIZE
	var room_x = int(new_pos.x / TILE_SIZE)
	var room_y = int(new_pos.y / TILE_SIZE)

	if room_x < 0 or room_x >= map_node.MAP_WIDTH:
		return
	if room_y < 0 or room_y >= map_node.MAP_HEIGHT:
		return
	# print(map_node.map)
	var room = map_node.map[room_y][room_x]

	if room["guarded"] and current_mask != room["mask_required_type"]:
		print("Wrong mask! Access denied.")
		return

	@warning_ignore("integer_division")
	target_position = Vector2(room_x, room_y) * TILE_SIZE + Vector2(TILE_SIZE/2,TILE_SIZE/2)

func set_mask(mask_type: MaskType):
	current_mask = mask_type
	update_mask_visual()

func update_mask_visual():
	match current_mask:
		MaskType.NONE:
			mask_sprite.visible = false

		MaskType.TRIANGLE:
			mask_sprite.texture = TRIANGLE_MASK
			mask_sprite.visible = true
			fit_sprite_to_tile(mask_sprite)

		MaskType.CIRCLE:
			mask_sprite.texture = CIRCLE_MASK
			mask_sprite.visible = true
			fit_sprite_to_tile(mask_sprite)

		MaskType.SQUARE:
			mask_sprite.texture = SQUARE_MASK
			mask_sprite.visible = true
			fit_sprite_to_tile(mask_sprite)

func fit_sprite_to_tile(sprite_node: Sprite2D):
	if sprite_node.texture == null:
		return

	var texture_size = sprite_node.texture.get_size()

	var scale_factor = min(
		TILE_SIZE / texture_size.x,
		TILE_SIZE / texture_size.y
	)

	sprite_node.scale = Vector2(scale_factor, scale_factor)
