extends Node
# This is an autoload script handling things related to track data and state.

signal track_changed()

const TRACKS_PATH = "res://assets/tracks/"
var _tracks = []
var _selected : int


func _ready():
	_load_tracks()
	_selected = 0
	emit_signal("track_changed")


func set_next_track():
	_selected = wrapi(_selected + 1, 0, _tracks.size())
	emit_signal("track_changed")


func set_previous_track():
	_selected = wrapi(_selected - 1, 0, _tracks.size())
	emit_signal("track_changed")


func get_current_track():
	return _tracks[_selected]["path"]


func get_current_track_name():
	return _tracks[_selected]["name"]


func _load_tracks():
	var loaded = []
	for path in _find_track_files():
		var file = File.new()
		file.open(path, File.READ)
		var track = _load_from_txt(file.get_as_text())
		var track_name = path.get_file().rstrip(".%s" % path.get_extension())
		if track.size() > 1:
			loaded.append({
					"name": track_name,
					"path": track,
					})
		else:
			print("Error in track file : ", path)
	
	if loaded:
		print("Successfully loaded ", loaded.size(), " tracks.")
		_tracks = loaded


func _load_from_txt(content):
	var used_cells = []
	var start
	# Load the content
	var lines = content.split("\n")
	for y in range(0, lines.size()):
		for x in range(0, lines[y].length()):
			if lines[y][x] == "s":
				start = Vector2(x,y)
			elif lines[y][x] == "x":
				used_cells.append(Vector2(x,y))
	# Build an oriented path from start cell going right first
	var path = [start]
	while used_cells.size() > 0:
		var next = __find_adjacent(path[-1], used_cells)
		if next == -1:
			print("Error while loading path. (Path is invalid)")
		else:
			path.append(used_cells[next])
			used_cells.remove(next)
	#print_debug("Loading map from txt. Starting at : ", start, " | Path : \n", path)
	return path


func __find_adjacent(coords, cells):
	for dir in [Vector2(1,0), Vector2(0,1), Vector2(-1,0), Vector2(0,-1)]:
		var idx = cells.find(coords + dir)
		if idx != -1:
			return idx
	return -1


func _find_track_files():
	var tracks = []
	var dir = Directory.new()
	if dir.open(TRACKS_PATH) == OK:
		dir.list_dir_begin(true, true)
		while true:
			var file = dir.get_next()
			if file == "":
				break
			if file.ends_with(".txt"):
				tracks.append(TRACKS_PATH + file)
		return tracks
	else:
		print("An error occured while trying to load tracks. (Folder not found)")