extends Node

@export_category("API LINKS")
@export var API_URL: String = "http://127.0.0.1:5000/api"
@export var API_SAVE_WORLD_URL: String = "http://127.0.0.1:5000/api/add_world"

# Local scripts
@onready var API = $"."
@onready var request = $"../HTTPRequest"
@onready var tilemap1 = $"../../Blocks"
@onready var tilemap2 = $"../../Wallpapers"


# Use the retrieved world data
func use_world_data(data: Dictionary):
	# Example: Print the retrieved data
	print(data)

	# Example: Apply the tilemap data (this is a simple example, you need to adjust it to your needs)
	for tilemap_data in data.tiles:
		var tilemap_name = tilemap_data.id
		var tilemap: TileMap = get_node("../../" + tilemap_name)
		for tile_info in tilemap_data.tiles:
			var position = tile_info.position
			var tile_id = tile_info.tile_id
			var tile_data = tile_info.tile_data
			tilemap.set_cell(0, position, tile_id)
			tilemap.set_cell_tile_data(0, position, tile_data)


# Function to gather all tile map data and add it to a json var
func gather_tilemap_data(tilemap: TileMap) -> Dictionary:
	var data = {}
	data["id"] = tilemap.name
	data["tiles"] = []

	for cell in tilemap.get_used_cells(0):
		var cell_data = {
			"position": cell,
			"tile_id": tilemap.get_cell_source_id(0, cell),
			"tile_data": tilemap.get_cell_tile_data(0, cell)
		}
		data["tiles"].append(cell_data)

	return data

# appends all tilemaps to array for json
func gather_all_tilemaps_data() -> Array:
	var all_data = []
	all_data.append(gather_tilemap_data(tilemap1))
	all_data.append(gather_tilemap_data(tilemap2))
	return all_data

# Send data to the api
func send_data_to_api(data: Array):
	var json = JSON.stringify(data)
	var headers = ["Content-Type: application/json"]
	request.request(API_URL, headers, HTTPClient.METHOD_POST, json)

func save_world_data():
	var data = {
		"name": "Example World",
		"description": "An example world with tilemaps",
		"creator_id": 1,
		"tilemap": "",
		"tilemap_width": tilemap1.get_used_rect().size.x,
		"tilemap_height": tilemap1.get_used_rect().size.y,
		"tiles": JSON.stringify(gather_all_tilemaps_data())
	}
	var json = JSON.stringify(data)
	var headers = ["Content-Type: application/json"]
	request.request(API_SAVE_WORLD_URL, headers, HTTPClient.METHOD_POST, json)
	pass


# Function to retrieve world data from the API
func retrieve_world_data(world_id: int):
	request.request(API_URL + "/get_world/" + str(world_id), [], HTTPClient.METHOD_GET)


func _ready():
	retrieve_world_data(1)

# Process the response from the HTTPRequest node
func _on_http_request_request_completed(result, response_code, headers, body):
	if response_code == 201:
		print("Data sent successfully!")
	elif response_code == 200:
		var json_instance = JSON.new()

		# Convert PackedByteArray to String
		var body_str = body.get_string_from_utf8()

		# Parse the JSON string
		var response_data = json_instance.parse(body_str)

		# Check if JSON parsing was successful
		if response_data.error != OK:
			print("Error:", response_data.error_string)
		else:
			# Ensure response_data.result is valid
			if typeof(response_data.result) == TYPE_DICTIONARY:
				print("World data retrieved successfully!")
				use_world_data(response_data.result)
			else:
				print("Error: Invalid JSON structure")

	else:
		print("Failed to send or retrieve data:", response_code)


godot 4 throwing error at "if response_data.error !=OK:
Invalid get index 'error' (on base: 'int').