extends Node2D

onready var interact_message = get_node("/root/Node2D/Hints/KeyPress/Interact") as HBoxContainer
onready var task = get_node("Task/UI") as Control
onready var progressbar = get_node("Task/UI/ProgressBar") as ProgressBar
onready var timer = get_node("Timer") as Timer

var rng = RandomNumberGenerator.new()

func _ready():
	rng.randomize()
	task.visible = false
	pass

func _physics_process(delta):	
	# Handle when player is around task
	for player in $Area2D.get_overlapping_bodies():
		if player is KinematicBody2D:
			# Open task if user presses E
			if Input.is_action_just_pressed("interact") and interact_message.visible and $Area2D.overlaps_body(player):
				print("Show!")
				Networking.move = false
				task.visible = !task.visible
		
			var distance = position.distance_to(player.position) * 0.004
			
			# GUI
			if distance < 0.11:
				interact_message.visible = true
			else:
				interact_message.visible = false
			
			# Light texture scale
			if distance < 0.2:
				$Light2D.energy = sqrt(4 * distance + 0.1)
				if distance >= 0.1:
					$Light2D.texture_scale = distance

func _on_Area2D_body_entered(body):
	interact_message.visible = true


func _on_Area2D_body_exited(body):
	interact_message.visible = false

func _on_Close_pressed():
	timer.stop()
	progressbar.value = 0
	task.visible = false
	Networking.move = true
	$Task/UI/Begin.disabled = false
	
# Change progressbar
func _on_Timer_timeout():
	# We finished!
	if progressbar.value >= 100:
		$Light2D.visible = false
		$Area2D/CollisionShape2D.disabled = true
		Networking.add_to_chat("You did task Wifi")
		_on_Close_pressed()
		
	timer.wait_time = rng.randf_range(0.1, 0.5)
	progressbar.value += rng.randf_range(1, 4.3)
	
	if progressbar.value >= 100:
		(get_node("/root/Node2D/Hints/Explosion") as VideoPlayer).visible = true
		(get_node("/root/Node2D/Hints/Explosion") as VideoPlayer).play()
		$Task/UI/Close.visible = false
		timer.wait_time = 3

# Download button was pressed
func _on_Begin_pressed():
	$Task/UI/Begin.disabled = true
	timer.start()
