extends CharacterBody3D


const WALK_SPEED = 2.0
const MOUSE_SENS = 0.002
var has_flashlight = false
var has_key = false
@onready var flashlight = $"../FlashLight"
@export var win: Node
var won = false
@export var win_position: Node

var mouse_mode = 2

func _ready():
	Input.set_mouse_mode(mouse_mode)

func _input(event):
	if !won:
		if event is InputEventMouseMotion and mouse_mode == 2:
			$Pivot.rotate_y(-event.relative.x*MOUSE_SENS)
			$Pivot/Camera.rotate_x(-event.relative.y*MOUSE_SENS)
		elif event.is_action_pressed("mode"):
			mouse_mode = mouse_mode ^ 1
			Input.set_mouse_mode(mouse_mode)
		elif event.is_action_pressed("alt") and has_flashlight:
			$Pivot/Camera/FlashLight/Klik.playing = true
			$Pivot/Camera/FlashLight/SpotLight3D.visible = !$Pivot/Camera/FlashLight/SpotLight3D.visible

func _physics_process(delta):
	if mouse_mode == 2 and !won:
		var input_dir = Input.get_vector("move_left", "move_right", "move_forward", "move_back")
		var direction = ($Pivot.transform.basis * Vector3(input_dir.x, 0, input_dir.y)).normalized()
		velocity.x = direction.x * WALK_SPEED
		velocity.z = direction.z * WALK_SPEED
		var bump = move_and_collide(velocity*delta)
		if bump and bump.get_collider() == win:
			won = true
			$Pivot/Camera/FlashLight.visible = false
			$Pivot/Camera.basis = Basis()
	elif won:
		var a = Quaternion($Pivot.transform.basis)
		var b = Quaternion(win_position.transform.basis)
		var c = a.slerp(b,delta*0.1)
		$Pivot.transform.basis = Basis(c)
		var d = win_position.position
		position = position.slerp(win_position.position, delta * 0.5)
		if (a - b).length() < 0.1 :
			$"../WorldEnvironment".environment.background_energy_multiplier += delta
			if $"../WorldEnvironment".environment.background_energy_multiplier > 2.0:
				$"../Einde/Thx".visible = true
			if $"../WorldEnvironment".environment.background_energy_multiplier > 10.0:
				get_tree().quit()

func _on_flash_light_input_event(_camera, event, _position, _normal, _shape_idx):
	if event is InputEventMouseButton and event.is_action_pressed("interact"):
		$Pivot/Camera/FlashLight.visible = true
		has_flashlight = true
		$Pickup.playing = true
		$".."/Gui.message("You can toggle the flashlight with right-mouse", "Flashlight")
		if flashlight:
			flashlight.visible = false
