extends Window

@onready var auth_url_clipboard_button = %AuthURLClipboardButton

@onready var auth_token_expiration_label = %AuthTokenExpirationLabel
@onready var auth_token_expiration_timer = %AuthTokenExpirationTimer
@onready var auth_token_expiration_time: int = 300
@onready var open_bot_settings_button = %OpenBotSettingsButton
@onready var open_read_me_button = %OpenReadMeButton

@onready var good_profile_image_button = %GoodProfileImageButton
@onready var bad_profile_image_button = %BadProfileImageButton
@onready var skip_tts_button = %SkipTTSButton

@onready var profile_image_queue_grid_container = %ProfileImageQueueGridContainer
@onready var profile_queue_notice_tween = create_tween().set_loops(0)
@onready var profile_queue_notice = $AdminBackground/MarginContainer/AdminContainer/ProfileImages/ProfileQueueNotice

@export var message_queue_manager: MessageQueueManager

@onready var twitch_connection_label = %TwitchConnectionLabel
@onready var youtube_live_connection_label = %YoutubeLiveConnectionLabel

@onready var bot_chat_message_line_edit = %BotChatMessageLineEdit

var _is_youtube_connected: bool = false

@onready var auth_url_string: String = ""

func _init():
	SignalBus.twitch_bot_authenticated.connect(_on_twitch_bot_authenticated)
	SignalBus.twitch_bot_not_configured.connect(_on_twitch_bot_not_configured)

	SignalBus.youtube_live_connected.connect(_on_youtube_live_connected)

	SignalBus.archive_mode_activated.connect(_on_archive_mode_activated)


func _ready():
	profile_queue_notice_tween.tween_property(profile_queue_notice, "visible", true, 0.75)
	profile_queue_notice_tween.tween_property(profile_queue_notice, "visible", false, 0.75)
	profile_queue_notice_tween.stop()

	good_profile_image_button.button_down.connect(approve_image)
	bad_profile_image_button.button_down.connect(deny_image)
	skip_tts_button.button_down.connect(func(): message_queue_manager.skip_tts_chatter())

	close_requested.connect(func(): SystemManager.quit())



	open_bot_settings_button.button_down.connect(func(): ConfigManager.open_settings_file())
	open_read_me_button.button_down.connect(func(): ConfigManager.open_readme_file())

	_connect_auth_button_signals()
	_update_auth_token_expiration_label()
	auth_token_expiration_timer.timeout.connect(_on_auth_token_expiration_timer_timeout)

	bot_chat_message_line_edit.text_submitted.connect(_broadcast_bot_message)

	if ConfigManager.get_setting("basic", "censor_images_until_approved"):
		UserMaterials.on_new_user_material_generated.connect(_add_profile_image_to_queue)
	else:
		%AutoApprovingWarningLabel.show()
		good_profile_image_button.hide()
		bad_profile_image_button.hide()


func _on_twitch_bot_authenticated():
	twitch_connection_label.add_theme_color_override("font_color", Color.html("#57e389"))
	twitch_connection_label.text = twitch_connection_label.text.replace("NOT ", "")
	auth_url_clipboard_button.disabled = true
	auth_url_clipboard_button.mouse_filter = Control.MOUSE_FILTER_IGNORE


func _on_youtube_live_connected():
	if not _is_youtube_connected:
		_is_youtube_connected = true
		youtube_live_connection_label.add_theme_color_override("font_color", Color.html("#57e389"))
		youtube_live_connection_label.text = youtube_live_connection_label.text.replace("NOT ", "")


func _on_archive_mode_activated():
	# hide everything first
	for control in HelperMethods.get_all_children(self):
		if control is Control:
			control.hide()
	# Only show what is needed
	_show_with_parents(auth_url_clipboard_button)
	_show_with_parents(twitch_connection_label)


func _show_with_parents(node: Node) -> void:
	var current := node
	while current:
		if current is CanvasItem:
			current.show()
		current = current.get_parent()

func _on_twitch_bot_not_configured():
	await ready
	for element in HelperMethods.get_all_children(self):
		if element is Control:
			element.hide()
	open_bot_settings_button.show()
	%BotNotConfiguredWarningLabel.show()
	open_read_me_button.show()

	var p = open_bot_settings_button.get_parent()
	while p and p is Control:
		p.show()
		p = p.get_parent()


func approve_image():
	profile_queue_notice_tween.stop()
	profile_queue_notice.hide()
	if profile_image_queue_grid_container.get_child_count():
		var oldest_child = profile_image_queue_grid_container.get_child(0)
		UserMaterials.unblur_material(oldest_child.name)
		oldest_child.queue_free()


func deny_image():
	profile_queue_notice_tween.stop()
	profile_queue_notice.hide()
	if profile_image_queue_grid_container.get_child_count():
		var oldest_child = profile_image_queue_grid_container.get_child(0)
		profile_image_queue_grid_container.move_child(oldest_child, -1)


func _add_profile_image_to_queue(new_user_material: ShaderMaterial):
	profile_queue_notice_tween.play()

	var new_grid_image = TextureRect.new()
	new_grid_image.custom_minimum_size = Vector2(64.0, 64.0)
	new_grid_image.expand_mode = TextureRect.EXPAND_IGNORE_SIZE
	new_grid_image.texture = new_user_material.get_shader_parameter("fill_texture")
	new_grid_image.name = new_user_material.resource_name
	profile_image_queue_grid_container.call_deferred("add_child",new_grid_image)


func _broadcast_bot_message(message_string: String):
	bot_chat_message_line_edit.placeholder_text = "Message Sent!"
	bot_chat_message_line_edit.clear()
	get_tree().get_first_node_in_group("Twitch").send_message_from_bot(message_string)
	await get_tree().create_timer(0.5).timeout
	bot_chat_message_line_edit.placeholder_text = "Enter Chat Message Here"


func _on_auth_token_expiration_timer_timeout():
	auth_token_expiration_time -= 1
	_update_auth_token_expiration_label()

	if auth_token_expiration_time <= 0:
		auth_token_expiration_timer.stop()
		auth_token_expiration_time = 0
		auth_token_expiration_label.visibility_layer = 0
		_update_auth_token_expiration_label()


func _update_auth_token_expiration_label():
	auth_token_expiration_label.text = "EXPIRES IN %s" % str(auth_token_expiration_time)


func _connect_auth_button_signals():
	SignalBus.authorization_url_ready.connect(update_auth_url_clipboard_button)
	auth_url_clipboard_button.mouse_entered.connect(func(): auth_url_clipboard_button.text = "COPY")
	auth_url_clipboard_button.mouse_exited.connect(func(): auth_url_clipboard_button.text = "AUTH URL")
	auth_url_clipboard_button.button_down.connect(func(): DisplayServer.clipboard_set(auth_url_string); auth_url_clipboard_button.text = "COPIED"; auth_token_expiration_label.visibility_layer = 0)


func update_auth_url_clipboard_button(new_url: String):
	auth_url_string = new_url
