using System;
using Unity.Behavior;
using UnityEngine;
using Action = Unity.Behavior.Action;
using Unity.Properties;
using TMPro;

[Serializable, GeneratePropertyBag]
[NodeDescription(name: "Change Text Bubble", story: "Set [TextBubble] text to [Text]", category: "Action/TextMeshPro", id: "826b76a1b58004a0dea5578ecdadf2f0")]
public partial class ChangeTextBubbleAction : Action
{
    [SerializeReference] public BlackboardVariable<GameObject> TextBubble;
    [SerializeReference] public BlackboardVariable<string> Text;
    [SerializeReference] public BlackboardVariable<float> DisplayTime = new BlackboardVariable<float>(2f);

    private float CurrentTime = 0f;

    protected override Status OnStart()
    {
        if (TextBubble.Value == null)
        {
            return Status.Failure;
        }

        CurrentTime = DisplayTime;

        TextBubble.Value.SetActive(true);

        return Status.Running;
    }

    protected override Status OnUpdate()
    {
        TextBubble.Value.transform.rotation = GetTextLookRotation();
        if (DisplayTime >= 0f && CurrentTime <= 0f)
        {
            TextBubble.Value.SetActive(false);
            return Status.Success;
        }

        TextBubble.Value.GetComponentInChildren<TextMeshProUGUI>(true).text = Text.Value;

        if (DisplayTime >= 0f)
        {
            CurrentTime -= Time.deltaTime;
            return Status.Running;
        }

        return Status.Success;
    }

    protected override void OnEnd()
    {
        TextBubble.Value.SetActive(false);
    }

    private Quaternion GetTextLookRotation()
    {
        Vector3 cameraForward = Camera.main.transform.forward;
        cameraForward.y = 0.0f;
        cameraForward.Normalize();
        return Quaternion.LookRotation(cameraForward);
    }
}

