#nullable enable
using System;
using UnityEngine;
using UnityEngine.UIElements;
namespace UVC.UIToolkit
{
///
/// 정수(int) 입력 필드 컴포넌트.
/// Unity IntegerField를 래핑하여 커스텀 스타일을 적용합니다.
/// -2,147,483,648 ~ 2,147,483,647 범위의 정수를 입력받습니다.
///
///
/// int(정수)란?
/// int는 32비트 부호 있는 정수 타입으로, 소수점이 없는 숫자를 저장합니다.
///
/// - 개수, 수량, 인덱스 등 정수 값에 사용
/// - 큰 숫자가 필요하면 UTKLongField 사용
/// - 소수점이 필요하면 UTKFloatField 사용
/// - Validation 함수를 통한 입력 검증 (FocusOut 시 자동 호출)
/// - 에러 상태 시 붉은 외곽선 + 에러 메시지 표시
///
///
///
/// C# 코드에서 사용:
///
/// // 기본 정수 필드 생성
/// var intField = new UTKIntegerField();
/// intField.label = "수량";
/// intField.Value = 10;
///
/// // 값 변경 이벤트
/// intField.OnValueChanged += (value) => {
/// Debug.Log($"수량: {value}");
/// };
///
/// // 라벨과 기본값을 지정하는 생성자
/// var countField = new UTKIntegerField("아이템 개수", 5);
///
/// // 현재 값 읽기/쓰기
/// int currentValue = intField.Value;
/// intField.Value = 20;
///
/// // 비활성화
/// intField.IsEnabled = false;
///
/// Validation (입력 검증):
///
/// // 검증 함수 설정 (Func)
/// var ageField = new UTKIntegerField("나이", 0);
/// ageField.ErrorMessage = "나이는 1~150 사이여야 합니다.";
/// ageField.Validation = () => ageField.Value >= 1 && ageField.Value <= 150;
/// // → FocusOut 시 자동으로 검증
/// // → 실패 시 붉은 외곽선 + 에러 메시지 표시, 통과 시 자동 해제
///
/// // 양수만 허용
/// var quantityField = new UTKIntegerField("수량", 0);
/// quantityField.ErrorMessage = "수량은 0보다 커야 합니다.";
/// quantityField.Validation = () => quantityField.Value > 0;
///
/// // 강제 검증 호출 (예: 폼 제출 버튼 클릭 시)
/// bool isValid = ageField.Validate();
/// if (!isValid) return; // 검증 실패
///
/// // 에러 수동 해제
/// ageField.ClearError();
///
/// // 에러 메시지 직접 설정 (Validation 없이, 서버 오류 등)
/// intField.ErrorMessage = "서버 오류가 발생했습니다.";
/// intField.ErrorMessage = ""; // 오류 제거
///
/// UXML에서 사용:
///
///
///
///
///
///
///
///
/// ]]>
/// Label Min-Width 설정:
///
/// // label이 있을 때 .unity-label의 min-width를 설정
/// var intField = new UTKIntegerField("수량");
/// intField.LabelMinWidth = 120f; // 120px
///
/// 실제 활용 예시 (인벤토리 수량):
///
/// // 인벤토리 아이템 수량 편집
/// var quantityField = new UTKIntegerField("보유 수량", item.Quantity);
/// quantityField.ErrorMessage = "수량은 0 이상이어야 합니다.";
/// quantityField.Validation = () => quantityField.Value >= 0;
/// quantityField.OnValueChanged += (newQty) => {
/// item.Quantity = newQty;
/// UpdateInventoryUI();
/// };
///
///
[UxmlElement]
public partial class UTKIntegerField : IntegerField, IDisposable
{
#region Constants
private const string USS_PATH = "UIToolkit/Input/UTKIntegerField";
#endregion
#region Fields
private bool _disposed;
private bool _isEnabled = true;
private string _errorMessage = "";
private float _labelMinWidth = -1f;
private Func? _validation;
private Label? _errorLabel;
#endregion
#region Events
/// 값 변경 이벤트
public event Action? OnValueChanged;
#endregion
#region Properties
/// 현재 값
public int Value
{
get => value;
set => this.value = value;
}
/// 에러 메시지. 비어있지 않으면 에러 상태로 표시
[UxmlAttribute("error-message")]
public string ErrorMessage
{
get => _errorMessage;
set
{
_errorMessage = value;
var hasError = !string.IsNullOrEmpty(value);
EnableInClassList("utk-integer-field--error", hasError);
UpdateErrorLabel(hasError ? value : null);
}
}
/// 검증 함수. FocusOut 시 호출되어 false 반환 시 ErrorMessage 표시
public Func? Validation
{
get => _validation;
set => _validation = value;
}
/// 활성화 상태
[UxmlAttribute("is-enabled")]
public bool IsEnabled
{
get => _isEnabled;
set
{
_isEnabled = value;
SetEnabled(value);
EnableInClassList("utk-integer-field--disabled", !value);
}
}
/// label이 있을 때 .unity-label의 min-width (px). -1이면 미설정
[UxmlAttribute("label-min-width")]
public float LabelMinWidth
{
get => _labelMinWidth;
set
{
_labelMinWidth = value;
ApplyLabelMinWidth();
}
}
///
/// 읽기 전용
///
public new bool isReadOnly
{
get => base.isReadOnly;
set
{
base.isReadOnly = value;
EnableInClassList("utk-integer-field--readonly", value);
}
}
#endregion
#region Constructor
public UTKIntegerField() : base()
{
UTKThemeManager.Instance.ApplyThemeToElement(this);
var uss = Resources.Load(USS_PATH);
if (uss != null)
{
styleSheets.Add(uss);
}
SetupStyles();
SetupEvents();
SubscribeToThemeChanges();
}
public UTKIntegerField(string label, int defaultValue = 0) : this()
{
this.label = label;
value = defaultValue;
}
#endregion
#region Setup
private void SetupStyles()
{
AddToClassList("utk-integer-field");
// label 설정 후 LabelMinWidth 적용
schedule.Execute(() => ApplyLabelMinWidth());
}
private void SetupEvents()
{
RegisterCallback>(OnFieldValueChanged);
RegisterCallback(OnFocusOut);
RegisterCallback(OnKeyDown, TrickleDown.TrickleDown);
}
private void SubscribeToThemeChanges()
{
UTKThemeManager.Instance.OnThemeChanged += OnThemeChanged;
RegisterCallback(OnAttachToPanelForTheme);
RegisterCallback(OnDetachFromPanelForTheme);
}
private void OnAttachToPanelForTheme(AttachToPanelEvent evt)
{
UTKThemeManager.Instance.OnThemeChanged -= OnThemeChanged;
UTKThemeManager.Instance.OnThemeChanged += OnThemeChanged;
UTKThemeManager.Instance.ApplyThemeToElement(this);
}
private void OnDetachFromPanelForTheme(DetachFromPanelEvent evt)
{
UTKThemeManager.Instance.OnThemeChanged -= OnThemeChanged;
}
private void OnThemeChanged(UTKTheme theme)
{
UTKThemeManager.Instance.ApplyThemeToElement(this);
}
private void ApplyLabelMinWidth()
{
if (string.IsNullOrEmpty(label)) return;
var labelElement = this.Q