using Godot;
using Sfs3.Client.Entities;

/**
 * Script attached to the main node in the BuddyListItem scene.
 */
public partial class BuddyListItem : PanelContainer
{
	[Export]
	public TextureRect buddyUnblockedIconRect;
	[Export]
	public TextureRect buddyBlockedIconRect;
	[Export]
	public Label nameLabel;
	[Export]
	public TextureButton chatButton;
	[Export]
	public Label chatButtonLabel;
	[Export]
	public TextureButton blockButton;
	[Export]
	public TextureButton unblockButton;
	[Export]
	public TextureButton removeButton;
	[Export]
	public TextureButton addButton;

	private static readonly Color DIMMED = new Color(1f, 1f, 1f, 0.25f);
	private static readonly Color AVAILABLE = new Color(0f, 0.8f, 0f, 1f);
	private static readonly Color AWAY = new Color(1f, 0.8f, 0f, 1f);
	private static readonly Color OCCUPIED = new Color(0.8f, 0f, 0f, 1f);

	private bool buddyBlocked = false;

	public bool BuddyBlocked => buddyBlocked;

	public void Update(Buddy buddy)
	{
		// Nickname
		nameLabel.Text = buddy.DisplayName;

		// Save blocked state
		// (see BuddyList.UpdateListItem method)
		buddyBlocked = buddy.IsBlocked;

		// If buddy is not blocked and is temporary, show add button and hide remove button
		bool showAddButton = !buddy.IsBlocked && buddy.IsTemp;
		addButton.Visible = showAddButton;
		removeButton.Visible = !showAddButton;

		// Status icon and buttons
		if (buddy.IsBlocked)
		{
			// State
			buddyBlockedIconRect.Visible = true;
			buddyUnblockedIconRect.Visible = false;
			buddyBlockedIconRect.Modulate = DIMMED;

			// Block/unblock buttons
			blockButton.Visible = false;
			unblockButton.Visible = true;

			// Chat button
			SetChatButtonEnabled(false);
			UpdateUnreadMsgCounter(0);
		}
		else
		{
			// State
			buddyBlockedIconRect.Visible = false;
			buddyUnblockedIconRect.Visible = true;

			// Block/unblock buttons
			blockButton.Visible = true;
			unblockButton.Visible = false;

			if (!buddy.IsOnline)
			{
				// State
				buddyUnblockedIconRect.Modulate = DIMMED;

				// Chat button
				SetChatButtonEnabled(false);
				UpdateUnreadMsgCounter(0);
			}
			else
			{
				// State
				var state = buddy.State;

				if (state == "Available")
					buddyUnblockedIconRect.Modulate = AVAILABLE;
				else if (state == "Away")
					buddyUnblockedIconRect.Modulate = AWAY;
				else if (state == "Occupied")
					buddyUnblockedIconRect.Modulate = OCCUPIED;

				// Chat button
				SetChatButtonEnabled(true);
			}
		}
	}

	public void UpdateUnreadMsgCounter(int cnt)
	{
		chatButtonLabel.Text = cnt > 0 ? cnt.ToString() : "";
	}

	private void SetChatButtonEnabled(bool enable)
	{
		chatButton.Disabled = !enable;
		chatButton.Modulate = enable ? Colors.White : DIMMED;
	}
}
