class_name ChannelCard
extends HBoxContainer

signal initialized

const THUMBNAIL_SIZE := Vector2(50, 50)
const THUMBNAIL_INTERPOLATION_METHOD: int = Image.INTERPOLATE_LANCZOS

export(String, FILE) var default_thumbnail_path = "res://icon.png"

# URL of the channel on the LBRY blockchain
var _channel_url: String
# All the resolved data for this `_channel_url`
var _data: Dictionary = {}
var _is_setup: bool = false
var _default_thumbnail := ImageTexture.new()
var _initialized: bool = false
var _async_helper := AsyncHelper.new(self)
onready var _channel_thumbnail_node: TextureRect = \
		find_node("ChannelThumbnail")
onready var _channel_title_node: Label = find_node("ChannelTitle")
onready var _channel_name_node: Label = find_node("ChannelName")


func init(channel_url: String) -> void:
	_channel_url = channel_url
	_initialized = true
	emit_signal("initialized")


func _ready() -> void:
	if not _initialized:
		yield(self, "initialized")
	
	var default_img: Image = load(default_thumbnail_path).get_data()
	# Make sure the thumbnail enters the scene as the correct size
	default_img.resize(int(THUMBNAIL_SIZE.x), int(THUMBNAIL_SIZE.y))
	_default_thumbnail.create_from_image(default_img)
	_channel_thumbnail_node.set_texture(_default_thumbnail)
	
	if not _is_setup and _channel_url != "":
		_setup()


func _setup() -> void:
	var tracker: Dictionary = _async_helper.connect_wrapped(
			SDK.resolve([_channel_url]), "completed")
	yield(_async_helper.wait_until_finished([tracker]), "completed")
	var resolve_response: Dictionary = tracker["result"]
	if resolve_response.has("result"):
		_data = resolve_response["result"].get(
				resolve_response["result"].keys()[0])
	
	var resources: Array = yield(_get_resources(), "completed")
	var channel_name: String = resources[0]
	var channel_title: String = resources[1]
	var thumbnail: ImageTexture = resources[2]
	
	# Update _channel_url to the short URL if it was found
	if resources[0] != "":
		_channel_url = "lbry://" + resources[0]
	
	if channel_title == "":
		channel_title = channel_name.substr(1).rsplit("#", true, 1)[0]
	
	if thumbnail == null:
		thumbnail = _default_thumbnail
	var thumbnail_img: Image = thumbnail.get_data()
	thumbnail_img.resize(int(THUMBNAIL_SIZE.x), int(THUMBNAIL_SIZE.y),
			THUMBNAIL_INTERPOLATION_METHOD)
	thumbnail.create_from_image(thumbnail_img)
	
	_channel_name_node.set_text(channel_name)
	_channel_title_node.set_text(channel_title)
	_channel_thumbnail_node.set_texture(thumbnail)
	set_tooltip(_channel_url)
	_is_setup = true


func _get_resources() -> Array:
	"""
	Returns:
		The channel name (String), channel title (String) and channel thumbnail
		(ImageTexture). If the channel name or title is not found, then an
		empty string. If the thumbnail could not be loaded or contained no
		data, then `null`
	"""
	var channel_name: String = ""
	var channel_title: String = ""
	var channel_thumbnail: ImageTexture = null
	var tracker: Dictionary
	
	channel_name = _data.get("short_url", "").trim_prefix("lbry://")
	channel_title = _data.get("value", {}).get("title", "")
	
	var channel_thumbnail_url: String = _data \
			.get("value", {}) \
			.get("thumbnail", {}) \
			.get("url", "")
	tracker = _async_helper.connect_wrapped(
			Requests.get_image(channel_thumbnail_url), "completed")
	yield(_async_helper.wait_until_finished([tracker]), "completed")
	var channel_thumbnail_img: Image = tracker["result"]
	if not channel_thumbnail_img.is_empty():
		channel_thumbnail = ImageTexture.new()
		channel_thumbnail.create_from_image(channel_thumbnail_img)
	return [channel_name, channel_title, channel_thumbnail]


func get_channel_url() -> String:
	return _get_tooltip()


func get_channel_name() -> String:
	return _channel_name_node.get_text()


func get_channel_title() -> String:
	return _channel_title_node.get_text()
