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

public class MetalDetector : MonoBehaviour
{
    public System.Action<float> OnMetalDetected;

    [SerializeField] float MaxRange;
    [SerializeField] float DefaultDelay = 1f;
    [SerializeField] float DelayMultiplier = 4f;
    [SerializeField] AnimationCurve DetectionCurve;
    [SerializeField] AudioClip[] SFXs;

    private List<MetalObject> _metalObjectsInRange;
    private SphereCollider _collider;
    private Vector3 _dirToNearest;
    private float _delay;

    float timer;

    private void Awake()
    {
        _metalObjectsInRange = new List<MetalObject>();
        _collider = GetComponent<SphereCollider>();
    }

    private void Update()
    {
        UpdateDelay();
        HandleTimer();
    }

    private void HandleTimer()
    {
        timer += Time.deltaTime;
        if (timer >= _delay * DelayMultiplier)
        {
            timer = 0;
            Detect();
        }
    }

    private void Detect()
    {
        GameObject go = new GameObject("Sonar SFX");
        AudioSource audio = go.AddComponent<AudioSource>();
        audio.spatialBlend = 0;
        audio.clip = SFXs[UnityEngine.Random.Range(0, SFXs.Length)];
        audio.Play();
        Destroy(go, 2f);

        //Sonar.PlayOneShot(SFXs[UnityEngine.Random.Range(0, SFXs.Length)]);
        OnMetalDetected?.Invoke(_dirToNearest.magnitude);
    }

    private void UpdateDelay()
    {
        if (_metalObjectsInRange.Count > 0)
        {
            _dirToNearest = Vector3.one * (MaxRange + 1);
            for (int i = 0; i < _metalObjectsInRange.Count; i++)
            {
                if (_metalObjectsInRange[i] == null) continue;
                Vector3 direction = _metalObjectsInRange[i].transform.position - transform.position;
                if (direction.magnitude < _dirToNearest.magnitude)
                {
                    _dirToNearest = direction;
                }
            }
            _delay = DetectionCurve.Evaluate(_dirToNearest.magnitude / MaxRange);
            Debug.DrawRay(transform.position, _dirToNearest, Color.red);
        }
        else
            _delay = float.MaxValue;

    }

    public void SetRange(float range)
    {
        MaxRange = range;
        _collider.radius = range;
    }

    private void OnTriggerEnter(Collider other)
    {
        MetalObject mo = other.GetComponent<MetalObject>();
        if (mo == null) return;

        _metalObjectsInRange.Add(mo);
    }

    private void OnTriggerExit(Collider other)
    {
        MetalObject mo = other.GetComponent<MetalObject>();
        if (mo == null) return;

        _metalObjectsInRange.Remove(mo);
    }
}
