using UnityEngine;
using UnityEngine.Events;

namespace Assets.Scripts.NohaMorte
{
    public class UserAgentExpiration : UserAgentBaseClass, IUserInputListener
    {
        [Header("Design in Editor")]
        [SerializeField]
        GameObject userAgentPrefabRoot;
        [SerializeField]
        float idelTimeThresholdBeforeExpiry;
        [SerializeField]
        UnityEvent expireEvent;

        [Header("Runtime Debug")]
        [SerializeField]
        float currentIdleTime;

        //unity call backs
        public void Update()
        {
            CheckIdleThreshold();
        }
        void LateUpdate()
        {
            //this always increases, but gets zeroed out at every user input
            currentIdleTime += Time.deltaTime;
        }

        public void ForceExpireAgent()
        {
            //do smth else here too if needed
            ExpireUserAgentPrefab();
        }

        public void ExpireUserAgentPrefab()
        {
            UsersInputListener usersInputListener = FindObjectOfType<UsersInputListener>();
            usersInputListener.RemoveAgent(userAgentManager);
            expireEvent?.Invoke();
            Destroy(userAgentPrefabRoot);
        }

        public void CheckIdleThreshold()
        {
            if (currentIdleTime > idelTimeThresholdBeforeExpiry) { ExpireUserAgentPrefab(); }
        }


        public void OnAnyUserInput()
        {
            //regardless, zero the timeIlde;
            currentIdleTime = 0;
        }
    }
}

//the user input script should broadcast or send this for any button press, most likely tie this with a VRPN_Button script
public interface IUserInputListener
{
    public void OnAnyUserInput();
}
