using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.UIElements;
using static Unity.Barracuda.TextureAsTensorData;
using static UnityEditor.PlayerSettings;

public class AudioManager : MonoBehaviour
{
    public static AudioManager instance { get; private set; }

    public List<AudioObject> m_AudioObjects = new List<AudioObject>();

    private void Awake()
    {
        if(instance != null && instance != this)
        {
            Destroy(this);
        } else
        {
            instance = this;
        }
    }

    public void FootStepAudio( Vector3 bp_Position, float magnitude, PhysicMaterial groundType)
    {
        if (!groundType.IsUnityNull())
            FindAudioObjectByType(groundType, magnitude, bp_Position);
    }

    private AudioObject FindAudioObjectByType(PhysicMaterial groundType, float mag, Vector3 pos)
    {
        // Check for PM match
        foreach(AudioObject obj in m_AudioObjects)
        {
            if(obj.m_GroundType.name == groundType.name)
            {
                if (mag > obj.m_VelcoityMin )
                {
                    int randomClip = (int)Random.Range(0, obj.m_AudioClip.Count - 1);
                    AudioClip randomPick = obj.m_AudioClip[randomClip];
                    // Play sound
                    if (randomPick != null)
                    {
                        float volume = Mathf.Lerp(0f, obj.m_Volume, (mag - obj.m_VelcoityMin) / (obj.m_VelcoityMax - obj.m_VelcoityMin));
                        CustomAudioOneShot(pos, randomPick, volume, obj.m_PitchMin, obj.m_PitchMax);
                    }
                }
            }
        }
        return null;
    }
    void CustomAudioOneShot(Vector3 position, AudioClip clip, float volume, float pitchMin, float pitchMax)
    {
       
        GameObject audioObject = new GameObject("FootstepAudio");
        audioObject.transform.position = position;

        // Add an AudioSource component to the GameObject
        AudioSource audioSource = audioObject.AddComponent<AudioSource>();

        // Set the AudioClip to play
        audioSource.clip = clip;

        // Adjust sound properties
        audioSource.volume = Mathf.Pow((volume), 2); // Adjust the volume (0.0f to 1.0f)
        audioSource.pitch = Random.Range(pitchMin, pitchMax);  // Randomize the pitch within a range (e.g., 0.9 to 1.1)
                                                       // You can adjust other properties here such as spatial blend, loop, etc.

        // Play the sound
        audioSource.Play();

        // Clean up the GameObject after the sound finishes playing
        Destroy(audioObject, clip.length);
    }
}