tool
extends SummerDayEditable
class_name SummerDayEditableTube

export(PoolVector2Array) var vertices = PoolVector2Array([
	Vector2(-0.4, -0.4),
	Vector2(0.1, -0.4),
	Vector2(0.1, 0.1),
	Vector2(-0.4, 0.1),
	
	Vector2(-0.1, -0.1),
	Vector2(0.4, -0.1),
	Vector2(0.4, 0.4),
	Vector2(-0.1, 0.4),
	])

var picked_point = -1


func _init():
	z_range.index = 0


func _check_for_selection_candidate(event: InputEvent) -> bool: # Virtual.
	if event is InputEventMouseButton:
		if event.button_index == BUTTON_LEFT and event.pressed:
			return _is_point_included(event.position)
	return false


func _interact(event: InputEvent) -> bool: # Virtual.
	
	if event is InputEventMouseButton:
		if event.button_index == BUTTON_LEFT:
			if event.pressed:
				_pick_point(event.position)
			else:
				picked_point = -1
	
	if event is InputEventMouseMotion:
		if picked_point != -1:
			
			vertices[picked_point] = event.position
			_update_table()
			update_interaction_hint()
	return true


func _update_table(): # Virtual.
	var rear_matrix = SummerDayMathHelper.plane_3d_to_xy(
		Vector3(1.0, 1.0, 1.0),
		Vector3(-1.0, 1.0, 1.0),
		Vector3(-1.0, -1.0, 1.0),
		Vector3(1.0, -1.0, 1.0),
		
		vertices[0], vertices[1], vertices[2], vertices[3]
	)
	
	var front_matrix = SummerDayMathHelper.plane_3d_to_xy(
		Vector3(1.0, 1.0, -1.0),
		Vector3(-1.0, 1.0, -1.0),
		Vector3(-1.0, -1.0, -1.0),
		Vector3(1.0, -1.0, -1.0),
		
		vertices[4], vertices[5], vertices[6], vertices[7]
	)
	
	table.apply_matrix(front_matrix, 0, 0)
	table.apply_matrix(rear_matrix, 0, 1)
	table.flush()


func _is_point_included(point: Vector2) -> bool: # Private.
	var convex_hull = Geometry.convex_hull_2d(vertices)
	return Geometry.is_point_in_polygon(point, convex_hull)


func _draw_interaction_hint():
	for i in range(4):
		var vertex_2d = vertices[i]
		var vertex = _with_z(vertex_2d, 0.0)
		draw_dot(vertex, Color.cornflower)
	for i in range(4, 8):
		var vertex_2d = vertices[i]
		var vertex = _with_z(vertex_2d, -1.0)
		draw_dot(vertex, Color.crimson)
	for i in range(4):
		draw_line(
			_with_z(vertices[i], 0.0),
			_with_z(vertices[wrapi(i + 1, 0, 4)], 0.0),
			Color.cornflower
		)
	for i in range(4):
		draw_line(
			_with_z(vertices[i], 0.0),
			_with_z(vertices[i + 4], -1.0),
			Color.cornflower,
			Color.crimson
		)
	for i in range(4):
		draw_line(
			_with_z(vertices[i + 4], -1.0),
			_with_z(vertices[wrapi(i + 5, 4, 8)], -1.0),
			Color.crimson
		)
	

func _pick_point(mouse_pos):
	var picked_point_so_far = -1
	var nearest_distance = 0.02
	for i in vertices.size():
		var distance = vertices[i].distance_to(mouse_pos)
		if distance < nearest_distance:
			nearest_distance = distance
			picked_point_so_far = i
	picked_point = picked_point_so_far


func _with_z(vector: Vector2, z: float) -> Vector3:
	return Vector3(vector.x, vector.y, z)
