extends Line2D

var idx: int
var accessor: GameScene.LineAccessor

var hovered: bool

var moveSpeed: float = rand_range(0.5,1.5)

signal line_clicked(id)

func _ready() -> void:
	accessor = get_parent().get_line(idx)
	
func _process(delta: float) -> void:
	var p0: Vector2 = accessor.get_point0()
	var p1: Vector2 = accessor.get_point1()
	points[0] = points[0].linear_interpolate(p0,delta*moveSpeed)
	points[1] = points[1].linear_interpolate(p1,delta*moveSpeed)
	
	if $Area2D/CollisionShape2D != null:
		$Area2D/CollisionShape2D.rotation = p0.angle_to(p1) + (0.5 * PI)
		$Area2D/CollisionShape2D.position = p0.linear_interpolate(p1,0.5)
		$Area2D/CollisionShape2D.shape.height = p0.distance_to(p1)
	
	var owner: int = accessor.get_owner()
	match owner:
		0:
			default_color = Color.gray
		1:
			default_color = Color.red
		2:
			default_color = Color.blue
			
	if hovered:
		default_color = default_color.lightened(0.2)

func _input(event: InputEvent) -> void:
	if event is InputEventMouseButton:
		if event.button_index == BUTTON_LEFT and event.pressed and hovered:
				emit_signal("line_clicked", idx)

func _on_Area2D_mouse_entered() -> void:
	hovered = true

func _on_Area2D_mouse_exited() -> void:
	hovered = false
