Files
AppleHillsProduction/Assets/Scripts/UI/CardSystem/StateMachine/Card.cs
2025-11-15 20:37:01 +01:00

123 lines
3.9 KiB
C#

using AppleHills.Data.CardSystem;
using Core.SaveLoad;
using UnityEngine;
namespace UI.CardSystem.StateMachine
{
/// <summary>
/// Main Card controller component.
/// Orchestrates the card state machine, context, and animator.
/// This is the single entry point for working with cards.
/// </summary>
public class Card : MonoBehaviour
{
[Header("Components")]
[SerializeField] private CardContext context;
[SerializeField] private CardAnimator animator;
[SerializeField] private AppleMachine stateMachine;
[Header("Configuration")]
[SerializeField] private string initialState = "IdleState";
// Public accessors
public CardContext Context => context;
public CardAnimator Animator => animator;
public AppleMachine StateMachine => stateMachine;
public CardData CardData => context?.CardData;
private void Awake()
{
// Auto-find components if not assigned
if (context == null)
context = GetComponent<CardContext>();
if (animator == null)
animator = GetComponent<CardAnimator>();
if (stateMachine == null)
stateMachine = GetComponentInChildren<AppleMachine>();
}
/// <summary>
/// Setup the card with data and optional initial state
/// </summary>
public void SetupCard(CardData data, bool isNew = false, string startState = null)
{
if (context != null)
{
context.SetupCard(data, isNew);
}
// Start the state machine with specified or default state
string targetState = startState ?? initialState;
if (stateMachine != null && !string.IsNullOrEmpty(targetState))
{
stateMachine.ChangeState(targetState);
}
}
/// <summary>
/// Setup for booster reveal flow (starts at IdleState, will flip on click)
/// </summary>
public void SetupForBoosterReveal(CardData data, bool isNew)
{
SetupCard(data, isNew, "IdleState");
}
/// <summary>
/// Setup for album placement (starts at PlacedInSlotState)
/// </summary>
public void SetupForAlbumSlot(CardData data, AlbumCardSlot slot)
{
SetupCard(data, false, "PlacedInSlotState");
// Set the parent slot on the PlacedInSlotState
var placedState = GetStateComponent<States.CardPlacedInSlotState>("PlacedInSlotState");
if (placedState != null)
{
placedState.SetParentSlot(slot);
}
}
/// <summary>
/// Transition to a specific state
/// </summary>
public void ChangeState(string stateName)
{
if (stateMachine != null)
{
stateMachine.ChangeState(stateName);
}
}
/// <summary>
/// Get a specific state component by name
/// </summary>
public T GetStateComponent<T>(string stateName) where T : AppleState
{
if (stateMachine == null) return null;
Transform stateTransform = stateMachine.transform.Find(stateName);
if (stateTransform != null)
{
return stateTransform.GetComponent<T>();
}
return null;
}
/// <summary>
/// Get the current active state name
/// </summary>
public string GetCurrentStateName()
{
if (stateMachine?.currentState != null)
{
return stateMachine.currentState.name;
}
return "None";
}
}
}