extends Area2D

var speed = 16
var x = 0
var new_x = 0
var fuel = 16
var limits = Vector2(4, 24)

func _process(delta):
	var rl = Input.is_mouse_button_pressed(1)
	var rr = Input.is_mouse_button_pressed(2)
	
	var mpos = get_global_mouse_position().snapped(Vector2(1,1))
	
	if rl and !rr:
#		if global_position.x > borders.x: 
		new_x += speed * delta
		if ceil(x) != ceil(new_x):
			x = new_x
			position.x -= 1
	if rr and !rl:
#		if global_position.x < borders.y: 
		new_x += speed * delta
		if ceil(x) != ceil(new_x):
			x = new_x
			position.x += 1
				
	position.x = clamp(position.x, limits.x, limits.y)
	
func on_area_entered(area):
	var t = area.type
	if t == "bonus":
		if area.bonus_name == "fuel":
			fuel_bonus_collect()
		area.collect()
	else:
		destroy()
		
func fuel_bonus_collect():
	fuel += 8
	fuel = clamp(fuel, 0, 16)
	get_parent().get_node("gul/fuelbar").value = fuel
	
func fuel():
	var t = $fuel_time
	t.start()
	while fuel >= 0:
		yield(t, "timeout")
		fuel -= 1
		t.start()
		get_parent().get_node("gul/fuelbar").value = fuel
	destroy()
		
func destroy():
	set_deferred("monitorable", false)
	set_deferred("monitoring", false)
	$sprite.visible = false
	var _exp = load("res://scenes/explossion.tscn").instance()
	_exp.global_position = global_position
	get_parent().add_child(_exp)
	get_parent().stop = true
	get_parent().restart()
	get_parent().damage()
	
func _ready():
	global_position = Vector2(15, 24)
	self.connect("area_entered", self, "on_area_entered")
	fuel()
