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

public class SawTrap : MonoBehaviour
{
    [Header("Parameters")]
    [Tooltip("The time the saw waits to move again after getting to one end")]
    [SerializeField] float _waitingTime = 0;
    [Tooltip("The time the saw takes to go from one point to another")]
    [SerializeField] float _travelTime = 0;
    [Tooltip("Initial delay to activate")]
    [SerializeField] float _lagTime = 0;
    
    [Header("References")]
    [SerializeField] Transform _endPoint = null;
    [SerializeField] Transform _saw = null;
    [SerializeField] SpriteRenderer _rail = null;

    [Header("SFX")]
    [SerializeField] [Range(-3, 3)] float _sfxPitch;

    bool _toEndPoint;
    float _waitingTimer = 0;
    float _lagTimer = 0;
    float _travelTimer = 0;
    AudioSource _audioSource;

    void Start() 
    {
        _saw.position = transform.position;
        _toEndPoint = true;
        _waitingTimer = _waitingTime;

        Vector2 __initialSize = _rail.size;
        __initialSize.x += Mathf.Abs(_endPoint.position.x - transform.position.x);
        _rail.transform.position = transform.position + (_endPoint.position - transform.position) / 2;
        _rail.size = __initialSize;

        _audioSource = GetComponent<AudioSource>();
        _audioSource.volume = _sfxPitch;
    }

    void Update() 
    {
        if (!(_lagTimer >= _lagTime))
        {
            _lagTimer += Time.deltaTime;
            return;
        }
        
        if (_waitingTimer >= _waitingTime)
        {
            _audioSource.pitch = _sfxPitch;
            _travelTimer += Time.deltaTime;
            
            float __ratio = _travelTimer / _travelTime;
            if (_toEndPoint)
            {
                _saw.position = Vector3.Lerp(transform.position, _endPoint.position, __ratio);
            }
            else
            {
                _saw.position = Vector3.Lerp(_endPoint.position, transform.position, __ratio);
            }
            
            if (__ratio >= 1)
            {
                _waitingTimer = 0;
                _travelTimer = 0;
                _toEndPoint = !_toEndPoint;
                _audioSource.pitch = 1;
            }
        }
        else
        {
            _waitingTimer += Time.deltaTime;
        }
    }
}
