class_name Character
extends Control

@onready
var panel: Panel = $Panel

@onready
var character_image: TextureRect = %CharacterTextureRect

@onready
var character_name_label: Label = %CharacterName

signal new_character_selected(img_texture: ImageTexture)

func set_character_name(character_name: String) -> void:
	panel.size = Vector2(240, 145)
	#margin.size = Vector2(240, 145)
	#margin set margin 15, 10, 15, 0
	character_name_label.text = character_name.split(".")[0]
	character_name_label.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
	var image_fetched: Callable = func image_fetched(image: PackedByteArray) -> void:
		var img: Image = Image.new()
		var err: Error = img.load_png_from_buffer(image)
		if err != OK:
			print(err)
			var err2: Error = img.load_jpg_from_buffer(image)
			if err2 != OK:
				print(err2)
		var new_image: ImageTexture = ImageTexture.new()
		new_image.set_image(img)
		character_image.custom_minimum_size = Vector2(200, 100)
		character_image.size = Vector2(200, 100)
		character_image.size_flags_horizontal = Control.SIZE_SHRINK_CENTER
		character_image.size_flags_vertical = Control.SIZE_SHRINK_CENTER
		character_image.expand_mode = TextureRect.EXPAND_FIT_WIDTH_PROPORTIONAL
		character_image.stretch_mode = TextureRect.STRETCH_KEEP_ASPECT_CENTERED
		character_image.texture = new_image
	Settings.make_request2("/character?name=" + character_name.uri_encode(), image_fetched, true)

func _input(event: InputEvent) -> void:
	if self.visible == true && Settings.character_select_open == true:
		if event is InputEventMouseButton && event.is_pressed():
			var evLocal: InputEvent = make_input_local(event)
			if Rect2(Vector2(0, 0), panel.size).has_point(evLocal.position):
				print(character_name_label.text)
				new_character_selected.emit(character_image.texture)
