extends Control

@onready var token_input = $VBoxContainer/HBoxContainer/TokenInput
@onready var status_label = $VBoxContainer/ConnectionStatusLabel
@onready var location_name_label = $VBoxContainer/LocationNameLabel
@onready var location_image = $VBoxContainer/LocationImage
@onready var location_desc_label = $VBoxContainer/LocationDescriptionLabel
@onready var log_label = $VBoxContainer/LogLabel

var socket = WebSocketPeer.new()
var http_request : HTTPRequest
var is_connected_to_host = false

func _ready():
	log_message("Godot PoC Started")
	http_request = HTTPRequest.new()
	add_child(http_request)
	http_request.request_completed.connect(_on_image_request_completed)

func _process(delta):
	socket.poll()
	var state = socket.get_ready_state()
	
	if state == WebSocketPeer.STATE_OPEN:
		if not is_connected_to_host:
			is_connected_to_host = true
			status_label.text = "Status: Connected"
			log_message("WebSocket Connected!")
			
		while socket.get_available_packet_count():
			var packet = socket.get_packet()
			var data = packet.get_string_from_utf8()
			var json = JSON.new()
			var error = json.parse(data)
			if error == OK:
				handle_message(json.get_data())
			else:
				log_message("Error parsing JSON: " + data)
				
	elif state == WebSocketPeer.STATE_CLOSED:
		if is_connected_to_host:
			is_connected_to_host = false
			status_label.text = "Status: Disconnected"
			log_message("WebSocket Disconnected")

func _on_connect_button_pressed():
	var token = token_input.text.strip_edges()
	if token == "":
		log_message("Please enter a token.")
		return
		
	var url = "wss://api-staging.echoesoftheash.com/ws/game/" + token
	log_message("Connecting to: " + url)
	var err = socket.connect_to_url(url)
	if err != OK:
		log_message("Error connecting to URL: " + str(err))
	else:
		status_label.text = "Status: Connecting..."

func handle_message(msg):
	# log_message("Received: " + str(msg.get("type")))
	
	if msg.get("type") == "location_update":
		var data = msg.get("data", {})
		var location = data.get("location", {})
		
		if location:
			update_location_ui(location)

func update_location_ui(location):
	location_name_label.text = location.get("name", "Unknown Location")
	location_desc_label.text = location.get("description", "")
	
	var image_url = location.get("image_url", "")
	if image_url != "":
		fetch_image(image_url)

func fetch_image(url):
	if url.begins_with("/"):
		url = "https://api-staging.echoesoftheash.com" + url
		
	log_message("Fetching image: " + url)
	http_request.cancel_request()
	http_request.request(url)

func _on_image_request_completed(result, response_code, headers, body):
	if result == HTTPRequest.RESULT_SUCCESS:
		var image = Image.new()
		var error = image.load_png_from_buffer(body)
		if error != OK:
			error = image.load_jpg_from_buffer(body)
		if error != OK:
			error = image.load_webp_from_buffer(body)
			
		if error == OK:
			var texture = ImageTexture.create_from_image(image)
			location_image.texture = texture
		else:
			log_message("Failed to load image texture")
	else:
		log_message("Failed to fetch image. Code: " + str(response_code))

func log_message(text):
	print(text)
	log_label.text += text + "\n"
