using UnityEngine;
using UnityEngine.Audio;
using System.Linq;
#if UNITY_EDITOR
using UnityEditor;
#endif


[AddComponentMenu("LillithRosePup/AudioLink Sys Audio")]
[RequireComponent(typeof(AudioSource))]
public class SystemAudioCapture : MonoBehaviour
{
    private AudioSource audioSource;
    [SerializeField] private string deviceName;
    [SerializeField] private AudioMixerGroup audioMixerGroup; // Assign a muted mixer group
    private int sampleRate = 48000;
    private int bufferSize = 1024;

    public AudioClip CapturedAudio => audioSource.clip;

    void Start()
    {
        audioSource = GetComponent<AudioSource>();
        audioSource.loop = true;
        audioSource.mute = false; // Allow processing
        audioSource.outputAudioMixerGroup = audioMixerGroup; // Route to a muted mixer group
        StartCapture();
    }

    private void StartCapture()
    {
        if (string.IsNullOrEmpty(deviceName)) return;

        if (Microphone.IsRecording(deviceName))
            Microphone.End(deviceName);

        audioSource.clip = Microphone.Start(deviceName, true, 10, sampleRate);
        while (Microphone.GetPosition(deviceName) <= 0) { } // Wait for microphone to initialize
        audioSource.Play(); // Ensure playback for Audio Link
    }

    public void RestartCapture()
    {
        if (Microphone.IsRecording(deviceName))
            Microphone.End(deviceName);
        StartCapture();
    }

#if UNITY_EDITOR
    [CustomEditor(typeof(SystemAudioCapture))]
    public class SystemAudioCaptureEditor : Editor
    {
        public override void OnInspectorGUI()
        {
            SystemAudioCapture script = (SystemAudioCapture)target;
            var devices = Microphone.devices;
            int selectedIndex = Mathf.Max(0, devices.ToList().IndexOf(script.deviceName));
            selectedIndex = EditorGUILayout.Popup("Audio Device", selectedIndex, devices);
            if (selectedIndex >= 0 && selectedIndex < devices.Length)
            {
                script.deviceName = devices[selectedIndex];
            }
            script.audioMixerGroup = (AudioMixerGroup)EditorGUILayout.ObjectField("Audio Mixer Group", script.audioMixerGroup, typeof(AudioMixerGroup), false);
            if (GUILayout.Button("Restart Capture"))
            {
                script.RestartCapture();
            }
            if (GUI.changed)
            {
                EditorUtility.SetDirty(script);
            }
            DrawDefaultInspector();
        }
    }
#endif
}
