class_name CoreChat
extends Control


# TODO a separate text display which displays latest message to prevent long tts messages from clogging up conversations. Only display when tts message is active. message_queue > 1
# I'll just use my old chat display until this is worked out
# TODO: Coin system to replace channel points. Store to file and add basic economy commands. I.E (!give username 5 // !buy redeem_item)
# Betting system should be activiated via UDP ping commands with presets or with a chat command for moderators to use.
# TODO log messages to file, include in archive description


@onready var twitch_chat_bot = $TwitchChatBot
@onready var admin_window = $AdminWindow
@onready var message_queue_manager = $MessageQueueManager

## Replaces message information with info from random list.
const DEBUG_RANDOM_USER: bool = false


signal send_message_to_queue(TwitchChatMessage)

func _ready():
	_load_cmdline_args()

	twitch_chat_bot.message_sent.connect(_preprocess_tts_message)
	UDPListener.on_youtube_chat.connect(_preprocess_youtube_tts_message)
	UDPListener.on_button_down.connect(_on_udp_command_received)



func _load_cmdline_args():
	var args = Array(OS.get_cmdline_args())
	if args.has("--archive"):
		SystemManager.is_archive_mode = true
		SignalBus.archive_mode_activated.emit()
		get_tree().root.size = Vector2i(50,50) # INFO Main window can't be hidden. Would've made more sense to switch which window is main. Just shrink it so it's out of the way


## INFO "printf command_keyword | nc -u -w0 127.0.0.1 5555" to call unfocused program (Wayland makes it difficult to have global hotkeys without registering proper shortcuts)
## Valid keywords (approve_image, deny_image, skip_chatter)
func _on_udp_command_received(message: String):
	match message:
		"approve_image":
			admin_window.approve_image()
		"deny_image":
			admin_window.deny_image()
		"skip_chatter":
			print("chatter skipped")
			message_queue_manager.skip_tts_chatter()


## Converts a YouTube Live message to function properly with the preexisting tts/chat display systems
func _preprocess_youtube_tts_message(user: String, message: String, profile_image: Texture2D):
	var formatted_message: TwitchChatMessage = TwitchChatMessage.new()

	# This gets called again since user may leave python script running but restart the CoreChatOverlay
	SignalBus.youtube_live_connected.emit()

	formatted_message.chatter_user_name = user.lstrip("@")
	formatted_message.chatter_user_id = user.lstrip("@")
	formatted_message.color = Color(1.0, 0.451, 0.451, 1.0).to_html(false)

	formatted_message.message = TwitchChatMessage.Message.new()
	formatted_message.message.text = message

	var fragment = TwitchChatMessage.Fragment.new()
	fragment.text = message
	fragment.type = "text"
	formatted_message.message.fragments = [fragment]

	UserMaterials.get_user_material(formatted_message.chatter_user_id, profile_image)

	# YouTube message is ready and can now be sent along
	_preprocess_tts_message(formatted_message)


func _preprocess_tts_message(message):

	MessageLogger.log_message(message)

	if DEBUG_RANDOM_USER:
		var random_user = await HelperMethods.debug_get_random_twitch_user(twitch_chat_bot.twitch_service)
		message["chatter_user_name"] = random_user["display_name"]
		message["chatter_user_id"] = random_user["id"]
		message["color"] = Color(randf(),randf(),randf()).to_html(false)

	var message_text = message.message.text


	## Filter out blocked prefixes (Right now just !)
	for prefix in ["!"]:
		if message_text.strip_edges().begins_with(prefix):
			return

	## Filter out bot messages from TTS if configured
	if message.chatter_user_login == ConfigManager.get_setting("client_auth", "bot_username") and ConfigManager.get_setting("basic", "prevent_bot_message_tts"):
		return


	if message_text.begins_with("@"): # INFO Move @username mention text to end of tts so speech sounds more natural
		var parts = message_text.split(" ")
		var first = parts[0]

		if first.begins_with("@"):
			parts.remove_at(0)
			parts.append(first)
			message_text = " ".join(parts)

	# NOTE links are filtered out both here and then again in the actual chatter script for the tts spoken text
	message.message.text = HelperMethods.sanitize_links(message_text) # Pack formatted text back in message object and send off to queue system


	if not SystemManager.is_archive_mode:
		send_message_to_queue.emit(message)
