using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SpikeTrap : MonoBehaviour
{
    [Header("Parameters")]
    [Tooltip("The time the spikes waits to activate again")]
    [SerializeField] float _waitingTime = 0;
    [Tooltip("Initial delay to activate")]
    [SerializeField] float _lagTime = 0;
    [Tooltip("The time the spikes stay active")]
    [SerializeField] float _activeTime = 0;
    
    [Header("References")]
    [SerializeField] GameObject _hitbox = null;
    [SerializeField] Animator _animator = null;

    [Header("SFX")]
    [SerializeField] AudioClip _sfx = null;

    float _waitingTimer = 0;
    float _lagTimer = 0;
    float _activeTimer = 0;
    bool _isActive = false;
    bool _isReady = false;
    AudioSource _audioSource;
    
    void Start() 
    {
        _waitingTimer = _waitingTime;
        _hitbox.SetActive(false);
        _waitingTimer = _waitingTime;
        _audioSource = GetComponent<AudioSource>();
    }

    void Update() 
    {
        if (!(_lagTimer >= _lagTime))
        {
            _lagTimer += Time.deltaTime;
            return;
        }

        if (_isActive)
        {
            _activeTimer += Time.deltaTime;
            if (_activeTimer >= _activeTime)
            {
                _isActive = false;
                _hitbox.SetActive(false);
                _activeTimer = 0;
                _animator.SetTrigger("Deactivate");
            }
            return;
        }
        
        if (_waitingTimer >= _waitingTime * 0.7f)
        {
            if (!_isReady)
            {
                _animator.SetTrigger("Ready");
                _isReady = true;
            }
        }
        if (_waitingTimer >= _waitingTime)
        {
            _isActive = true;
            _isReady = false;
            _hitbox.SetActive(true);
            _waitingTimer = 0;
            _animator.SetTrigger("Activate");
            _audioSource.PlayOneShot(_sfx);
        }
        else
        {
            _waitingTimer += Time.deltaTime;
        }
    }
}
