import { observer } from 'mobx-react';
import { useAudioX } from './audiox/AudioX';
import { MicrophoneOption } from './audiox/models/Microphone';
import { Select, SelectOption } from '../Select';
import { useEffect } from 'react';

/**
 * The props for the MicrophoneSelector component
 */
interface MicrophoneSelectorProps {
  /**
   * The id of the select component
   */
  id: string;
  /**
   * A function that is called when the selected microphone changes.
   * @optional by default the microphone is changed in the AudioX library
   * @param value the value of the selected microphone
   * @returns
   */
  onChange?: (value: string) => void;
}
/**
 * A select component for selecting a microphone.
 * This is to be used with the AudioX library.
 * Note: For this component to work, the AudioX library must be initialized and
 * the microphone must be enabled. The user must also grant permission to
 * use the microphone.
 */
export const MicrophoneSelector = observer((props: MicrophoneSelectorProps) => {
  const { id, onChange } = props;
  const { microphone } = useAudioX();
  const options: SelectOption[] = microphone.microphoneOptions.map(
    (option: MicrophoneOption) => ({
      value: option.value,
      label: option.label
    })
  );

  useEffect(() => {
    microphone.init();
  });

  return (
    <Select
      id={id}
      options={options}
      onChange={(value) => {
        const option = microphone.microphoneOptions.find(
          (option) => option.value === value
        );
        if (option) {
          microphone.onMicrophoneChange(option);
        }
        if (onChange) {
          onChange(value);
        }
      }}
    />
  );
});
