extends Spatial

onready var tiles : GridMap = get_node("/root/Level/Map/Tiles")

onready var camera : Camera = get_node("/root/Level/Camera")

func mouse_position():
	var position_2d = get_viewport().get_mouse_position()
	var drop_plane  = Plane(Vector3(0, 1, 0), 1)
	var position_3d = drop_plane.intersects_ray(
							 camera.project_ray_origin(position_2d),
							 camera.project_ray_normal(position_2d))
	
	return position_3d

func position_to_string(position : Vector3):
	return str([int(round(position.x)), int(round(position.y)), int(round(position.z))])
	
export var TILE_OFFSET : Vector3 = Vector3(0.5, 0, 0.5)

func world_to_grid_position(position : Vector3):
	position += Vector3(TILE_OFFSET.x * tiles.cell_size.x, 
						TILE_OFFSET.y * tiles.cell_size.y, 
						TILE_OFFSET.z * tiles.cell_size.z)
	
	var diagonal_steps_amount = position.z / (2 * tiles.cell_size.z)
	var forward_steps_amount = (position.x - diagonal_steps_amount * tiles.cell_size.x) \
							   / (2 * tiles.cell_size.x)
	
	var hex_ceil_z = int(round(diagonal_steps_amount))
	var hex_ceil_x = int(round(forward_steps_amount + hex_ceil_z / 2))
	
	var row_is_moved = (int(abs(hex_ceil_z)) % 2 == 1) 
	
	return Vector3(int(hex_ceil_x * 2 + (sign(hex_ceil_z) if row_is_moved else 0.0) - 1), 0, int(hex_ceil_z * 2 - 1))

func grid_to_world_position(position : Vector3):
	return tiles.map_to_world(int(round(position.x)), int(round(position.y)), int(round(position.z)))

func spawn_on_position(scene, world_position : Vector3):
	var instance = scene.instance()
	add_child(instance)
	instance.translation = grid_to_world_position(world_position)
	return instance
