tool
extends Node2D

class_name GameMap

var ship_direction = 0
var ship_speed = 0

var current_ship_direction = 0
var current_ship_speed = 0

const SPEED_EASE = 0.5
const DIRECTION_EASE = 0.5
const EPSILON = 0.01

const ProbeElectricity = preload("res://Actors/Systems/Electricity/ElectricProbe.tscn")

onready var tilemaps = [ $base, $cables, $floor, $walls ]

onready var pois = $pois

export var unlit = false setget set_unlit

export var shadow_intensity = 0.2

func _ready():
	if Engine.editor_hint:
		return
	$editor.queue_free()
	set_unlit(false)
	
	# Electricity setup
	make_electric_probes($cables, "Wire")

func _process(delta: float):
	if Engine.editor_hint:
		return

	# Ease ship speed/direction changes
	if abs(ship_direction - current_ship_direction) < EPSILON:
		current_ship_direction = ship_direction
	else:
		current_ship_direction = lerp(current_ship_direction, ship_direction, delta * DIRECTION_EASE)
	if abs(ship_speed - current_ship_speed) < EPSILON:
		current_ship_speed = ship_speed
	else:
		current_ship_speed = lerp(current_ship_speed, ship_speed, delta * SPEED_EASE)
		set_engine_strength(current_ship_speed)
	$deepspace.rotation = current_ship_direction-PI/2
	$deepspace.region_rect.position += Vector2(sin(current_ship_direction), cos(current_ship_direction)) * current_ship_speed * delta

# Lighting

func set_unlit(val: bool):
	unlit = val

# Engine related functions

func set_engine_strength(val: float):
	# Set energy strength to current speed
	for child in $engines.get_children():
		if child is GameObjectEngine:
			var engine = child as GameObjectEngine
			engine.strength = val

# Tileset related functions

func make_electric_probes(tilemap: TileMap, tile_name: String):
	var tile_id = tilemap.tile_set.find_tile_by_name(tile_name)
	for cell in tilemap.get_used_cells_by_id(tile_id):
		var coord = tilemap.map_to_world(cell)
		var probe = ProbeElectricity.instance()
		probe.position = coord
		tilemap.add_child(probe)

func get_pois(type_filter, class_filter) -> Array:
	var filtered = []
	for child in $pois.get_children():
		if type_filter != null and child.poitype != type_filter:
			continue
		if class_filter != null and child.poiclass != class_filter:
			continue
		filtered.append(child)
	return filtered
