from random import randint
import fxconv
import json
import pathlib
import csv

def convert(input, output, params, target):
	if params["custom-type"] == "map":
		convert_map(input, output, params, target)
		return 0
	else:
		return 1

def convert_map(input, output, params, target):
	data = json.load(open(input, "r"))

	#find the tileset in use. it's a relative path (like ../tileset.tsx)
	nameTileset = data["tilesets"][0]["source"].replace(".tsx","")
	print(nameTileset)
	#the name of the tileset without the .something
	nameTilesetFree = nameTileset.split("/")[-1]
	#count the number of "back" (cd ..) to locate the tileset on the computer
	nbRetour = nameTileset.count("..")+1
	#create the tileset absolute path 
	tilesetPath = "/".join(input.split("/")[:-nbRetour]) + "/" + nameTileset + ".json"

	tileset = open(tilesetPath, "r")
	data_tileset = json.load(tileset)
	tileset_size = data_tileset.get("columns")
	tileset.close()

	#find the ID of the first tile in the walkable tileset ()
	indexWalkable = data["tilesets"][1]["firstgid"]
	print(indexWalkable)

	#Extract from the json the width, height
	w, h = data["width"], data["height"]

	#nbTileLayer is the number of "true" layers (without ObjectsLayer)
	nbTilelayer = ["data" in i for i in data["layers"]].count(True) - 1
	print( nbTilelayer)

	structMap = fxconv.Structure()

	structMap += fxconv.u32(w) + fxconv.u32(h) + fxconv.u32(nbTilelayer)
	structMap += fxconv.ref(f"img_{nameTilesetFree}")
	structMap += fxconv.u32(tileset_size)

	walk_data = bytes()
	layer = data["layers"][nbTilelayer]
	for tile in layer["data"]:
		if tile == 0: walk_data += fxconv.u16(tile)
		else : walk_data += fxconv.u16(tile-indexWalkable)

	structMap += fxconv.ptr(walk_data)

	#generate the array of tiles from the layer
	for i in range(nbTilelayer):
		print(i)
		layer_data = bytes()
		layer = data["layers"][i]
		for tile in layer["data"]:
				layer_data += fxconv.u16(tile-1)

		structMap += fxconv.ptr(layer_data)

	#generate !
	fxconv.elf(structMap, output, "_" + params["name"], **target)