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

using DXLib.Utils;

namespace DXLib.UI.Form.Control;

/*
 * A form control used to input positive numbers. Note that the value is handled as a string and supports leading zeroes.
 */
public class DXNumericField : DXTextField
{
	/* Properties */
	public int? Number { get => DXUtils.ConvertToInt( Text ); set => Text = value?.ToString(); }

	public int MinValue { get; set; }
	public int MaxValue { get; set; }

	/* Fields */
	private int changeCount;

	/* Methods */
	public DXNumericField()
	{
		// Configure control
		textField.Keyboard = Keyboard.Numeric;

		// Defaults
		MaxLength = 5;
	}

	// Configures numeric specific error hint text
	protected override void SetHintType( HintType type )
	{
		base.SetHintType( type );

		string text = type switch
		{
			// 'Foo must be greater than X'
			HintType.RequiredMin => DXString.Get( "form.hint.int.minimum", Title, MinValue ),
			
			// 'Foo must be between X and Y'
			HintType.RequiredRange => DXString.Get( "form.hint.int.range", Title, MinValue, MaxValue ),
			
			_ => null
		};

		hintLbl.Text = text!;
	}

	// Determines if current value is valid and within min-max range
	private bool IsInRange()
	{
		return DXUtils.IsValidNumber( Text ) && (Number >= MinValue) && (Number <= MaxValue);
	}

	/* Abstracts */

	// Only valid if integer in range or optional and empty
	public override bool IsValid()
	{
		return (!IsRequired && !HasValue()) || IsInRange();
	}

	/* Event Callbacks */

	// Text editing occurred
	protected override void OnTextChanged( object sender, TextChangedEventArgs args )
	{
		// Valid entry, proceed as normal
		if ( DXUtils.IsValidNumber( Text ) || string.IsNullOrEmpty( Text ) )
		{
			if ( changeCount > 0 )
			{
				OnChange();
			}

			changeCount++;
		}
		// Reject invalid entry
		else
		{
			Text = args.OldTextValue;
		}
	}
}

//
