using System.Collections;
using System.Collections.Generic;
using FMODUnity;
using Ktyl.Util;
using UnityEngine;
using UnityEngine.Events;

[RequireComponent(typeof(BoxCollider))]
public class PressurePlate : MonoBehaviour
{
    [SerializeField] private float _triggerDelay = 2.0f;
    [SerializeField] private float _resetDelay = -1f;
    [SerializeField] private SerialFloat _objectTimeScale;
    [SerializeField] private GameObject _graphics;
    [SerializeField]
    [EventRef]
    private string _sfx;

    public UnityEvent OnPress => _onPress;
    [SerializeField] private UnityEvent _onPress;

    public UnityEvent OnReset => _onReset;
    [SerializeField] private UnityEvent _onReset;
    
    private bool opened;
    
    private float? triggered = null;

    private void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("Player") && !triggered.HasValue)
        {
            triggered = Time.time;
            _onPress.Invoke();
            RuntimeManager.PlayOneShot( _sfx, transform.position );
            _graphics.SetActive(false);
        }
    }

    private void OnTriggerExit(Collider other)
    {
        // ignore 
        if (_resetDelay < 0) return;
        
        if(other.CompareTag("Player") && triggered.HasValue)
        {
            StartCoroutine(Reset());
        }
    }

    private IEnumerator Reset()
    {
        var elapsed = 0f;
        while (elapsed < _resetDelay)
        {
            elapsed += Time.deltaTime * _objectTimeScale;
            yield return null;
        }
        
        ResetImmediate();
    }

    public void ResetImmediate()
    {
        triggered = null;
        _graphics.SetActive(true);
        _onReset.Invoke();
    }
}