extends Node

var _user_materials: Dictionary = {}
var _base_shader_material: ShaderMaterial
const BLURRED_AMOUNT: float = 5.0


@onready var twitch_bot = get_tree().get_first_node_in_group("twitch_bot")


signal on_new_user_material_generated(material: ShaderMaterial)

func _ready():
	_base_shader_material = load("uid://doly3cv8lr16s")


func get_user_material(user_id_string: String, provided_texture: Texture2D = null) -> ShaderMaterial:
	if _user_materials.has(user_id_string):
		return _user_materials[user_id_string]

	var mat := _base_shader_material.duplicate() as ShaderMaterial
	mat.resource_name = user_id_string

	var tex: Texture2D
	# provided_texture is only ever going to be used for YouTube messages.
	if provided_texture != null:
		tex = provided_texture
		mat.set_shader_parameter("is_youtube", true)
	else:
		# Call twitch_bot method to get image
		tex = await _user_image_from_id(user_id_string)

	mat.set_shader_parameter("fill_texture", tex)
	mat.set_shader_parameter("blur_strength", BLURRED_AMOUNT if ConfigManager.get_setting("basic", "censor_images_until_approved") else 0.0)

	on_new_user_material_generated.emit(mat)
	_user_materials[user_id_string] = mat
	return mat


func unblur_material(user_id_string: String):
	if _user_materials.has(user_id_string):
		var unblur_tween = create_tween()
		#NOTE Had no idea lambda functions could be used in tween_method(). I've always had to setup helper methods. This new syntax is way cleaner!
		unblur_tween.tween_method( func(value): _user_materials[user_id_string].set_shader_parameter("blur_strength", value), BLURRED_AMOUNT, 0.0, 1.0).set_trans(Tween.TRANS_CUBIC)


# TWITCH PROFILE IMAGE
func _user_image_from_id(user_id_string: String) -> Texture2D:
	var user = await twitch_bot.twitch_service.get_user_by_id(user_id_string)
	return await twitch_bot.twitch_service.load_profile_image(user)
