extends Node

var card: Node


func _ready() -> void:
	card = get_parent()

	if _load_card() != OK:
		# TODO: No need to push another error as the failure state of loading does that already,
		# if the card is not cached, perhaps a placeholder blank card can be used instead?
		# Setting that up can be put here later...
		push_error("Failed to load card.")


func _load_card() -> Error:
	if _load_data() != OK:
		return FAILED

	if _load_image() != OK:
		return FAILED

	return OK


func _load_data() -> Error:
	var cached_json = FileAccess.get_file_as_string(
		"user://card_cache/" + card.card_info["id"] + "/card.json"
	)

	if cached_json.is_empty():
		push_error("%s\nCard json data was not found in cache" % card.error("CACHE"))
		return FAILED

	var card_json = JSON.parse_string(cached_json)

	if card_json == null:
		push_error("%s\nCard json data is could not be parsed as valid json" % card.error("DATA"))
		return FAILED

	card.card_info["name"] = card_json["name"]
	card.card_info["type"] = card_json["type_line"]
	card.card_info["desc"] = card_json["oracle_text"]
	card.card_info["cost"] = card_json["mana_cost"]

	return OK


func _load_image() -> Error:
	var cached_img = FileAccess.get_file_as_bytes(
		"user://card_cache/" + card.card_info["id"] + "/card.png"
	)

	if cached_img.is_empty():
		push_error("%sCard on-board image was not found in cache" % card.error("CACHE"))
		return FAILED

	var cache_image = Image.new()
	var image_status: Error = cache_image.load_png_from_buffer(cached_img)

	if image_status != OK:
		push_error("%sCard on-board image failed to load correctly" % card.error("IMAGE"))
		return FAILED

	card.cached_image = cache_image

	var image = Image.new()
	image_status = image.load_png_from_buffer(cached_img)

	if image_status != OK:
		push_error("%sCard on-board image failed to load correctly" % card.error("IMAGE"))
		return FAILED

	var size = card.colission_size()
	image.resize(int(size.x), int(size.y), Image.INTERPOLATE_LANCZOS)

	var image_texture = ImageTexture.new()
	image_texture.set_image(image)

	var card_sprite = card.get_node("Sprite2D")
	card_sprite.texture = image_texture

	return OK