/* 
 * Copyright (c)2009-2025 DemiVision, LLC. All Rights Reserved. The information 
 * herein is the CONFIDENTIAL and PROPRIETARY information of DemiVision, LLC. 
 */

using DXLib.UI;
using DXLib.UI.Control;
using DXLib.UI.Form.Control;

using DXLib.Data;

namespace iStatVball3;

/*
 * A custom textfield that adds a badge indicating the link status (none, pending, granted) of a corresponding
 * permission link.
 */
public class LinkField : DXTextField
{
	/* Constants */

	// Color for each link status
	public static readonly Color[] StatusColors =
	{
		DXColors.Dark4,
		DXColors.Warn,
		DXColors.Positive,
		DXColors.Positive
	};

	/* Properties */

	// Updates field text/status from specified link(s)
	public Link Link { set => Update( value ); }
	public IList<Link> Links { set => Update( value ); }

	/* Fields */
	private bool isList;

	// UI controls
	private readonly DXIcon icon;

	/* Methods */
	public LinkField()
	{
		// Status icon
		icon = new DXIcon
		{
			Resource = "status",

			BackgroundColor = LinkForm.DefaultColor,
			Size = 26,

			Horizontal = LayoutOptions.End,
			Vertical = LayoutOptions.Center
		};

		// Defaults
		UpdateStatus( Link.StatusType.None );

		// Requires network
		IsDisabled = !DXData.HasConnection();
	}

	// Post-construction initialization
	public override void Init()
	{
		base.Init();

		// Defaults
		Type = isList ? TextType.EmailList : TextType.Email;
		Hint = isList ? HintType.EmailList : HintType.Email;

		MinLength = 1;
		MaxLength = isList ? 256 : 64;

		// Layout
		Add( icon, 0, 1 );
	}

	// Updates text/status from specified link
	private void Update( Link link )
	{
		isList = false;

		Text = link?.Username;
		UpdateStatus( link?.Status );
	}

	// Updates text/status from specified links
	private void Update( IList<Link> links )
	{
		isList = true;

		Text = Link.GetText( links );
		UpdateStatus( Link.GetStatus( links ) );
	}

	// Updates current link status (color)
	private void UpdateStatus( Link.StatusType? status )
	{
		int index = (int)(status ?? Link.StatusType.None);

		icon.Color = StatusColors[ index ];
	}

	// Disables link specific controls
	public override void SetDisabled( bool disabled )
	{
		base.SetDisabled( disabled );

		icon.Opacity = disabled ? DisabledOpacity : 1.0;
	}

	/* Abstracts */

	// Validates current user not linking to themselves
	public override bool IsValid()
	{
		return base.IsValid() && !Shell.CurrentUser.Username.Equals( Text );
	}
}

//
