extends Node2D

const TiledMapReader = preload("../addons/vnen.tiled_importer/tiled_map_reader.gd")

# Declare member variables here. Examples:
# var a = 2
# var b = "text"
var Downloader = preload("res://lib/Downloader.gd")
var mapLoaded = ""
var mapImported = false
var toDownload = {}
var downloader

func init():
	downloader = Downloader.new()
	downloader.connect("download_done", self, "_on_downloader_done")
	downloader.connect("download_failed", self, "_on_downloader_error")

func _on_downloader_done(url):
	toDownload.erase(url)
	print(url+" saved")
	if downloader.urlToFilePath(url).split(".")[-1] == "json":
		mapLoaded = downloader.urlToFilePath(url)
		resolveMap(url)

func _on_downloader_error(url, err):
	print("error saving "+url)

# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
	if mapLoaded and len(toDownload) == 0 and not mapImported:
		importMap()

func getMap(url):
	mapImported = false
	toDownload[url] = OS.get_unix_time()
	downloader.download(url)
	
func resolveMap(url):
	var file=File.new()
	var error = file.open(mapLoaded, File.READ)
	if error != OK:
		print("error resolving map: ", error)
	while not file.eof_reached():
		var line = file.get_line()
		if "\"image\"" in line:
			var geturl = line.split("\"")[-2]
			if not "http" in geturl:
				geturl = downloader.getBaseUrl(url)+"/"+geturl
			toDownload[geturl] = OS.get_unix_time()
			downloader.download(geturl)
	file.close()
	
func importMap():
	print("importing map: ", mapLoaded)
	var map_reader = TiledMapReader.new()
	var options = {}
	options.add_background = true
	options.collision_layer = 1
	options.custom_properties = true
	options.save_tiled_properties = false
	options.tile_metadata = false
	options.uv_clip = true
	# Offset is only optional for importing TileSets
	options.apply_offset = true
	var scene = map_reader.build(mapLoaded, options)
	scene.name="TMX"
	add_child(scene, true)
	mapImported = true
