import React__default, { useState, useEffect, useCallback, useContext, createContext } from 'react';
import { u as useLocalization } from '../LocalizationContext-b2390bf8.js';
import Modal from '../ui/Modal.js';
import { B as BROWSER_SUPPORT_MIME_TYPE_LIST, h as VOICE_RECORDER_AUDIO_BIT_RATE, b as VOICE_MESSAGE_FILE_NAME, c as VOICE_MESSAGE_MIME_TYPE } from '../consts-33537265.js';
import useSendbirdStateContext from '../useSendbirdStateContext.js';
import '../stringSet-eefbc798.js';
import '../index-67135027.js';
import 'react-dom';
import '../index-896545a0.js';
import '../ui/Button.js';
import '../index-4372fcec.js';
import 'prop-types';
import '../ui/Icon.js';
import '../ui/IconButton.js';
import '../_rollupPluginBabelHelpers-4f8ebde4.js';
import '../MediaQueryContext-b4904a2e.js';
import '../withSendbird.js';

// Input props of VoiceRecorder

// Output of VoiceRecorder

const noop = () => {/* noop */};
const Context = /*#__PURE__*/createContext({
  start: noop,
  stop: noop,
  isRecordable: false
});
const VoiceRecorderProvider = props => {
  var _BROWSER_SUPPORT_MIME;
  const {
    children
  } = props;
  const {
    config
  } = useSendbirdStateContext();
  const {
    logger,
    isVoiceMessageEnabled
  } = config;
  const [mediaRecorder, setMediaRecorder] = useState(null);
  const [isRecordable, setIsRecordable] = useState(false);
  const [permissionWarning, setPermissionWarning] = useState(false);
  const {
    stringSet
  } = useLocalization();
  const checkPermission = () => {
    try {
      // Type '"microphone"' is not assignable to type 'PermissionName'.ts(2322)
      // this is typescript issue
      // https://github.com/microsoft/TypeScript/issues/33923
      // @ts-expect-error
      navigator.permissions.query({
        name: 'microphone'
      }).then(result => {
        if (result.state === 'denied') {
          logger.warning('VoiceRecorder: Permission denied.');
          setPermissionWarning(true);
        }
      });
    } catch (error) {
      logger.warning('VoiceRecorder: Failed to check permission.', error);
    }
  };
  const browserSupportMimeType = (_BROWSER_SUPPORT_MIME = BROWSER_SUPPORT_MIME_TYPE_LIST.find(mimeType => MediaRecorder.isTypeSupported(mimeType))) !== null && _BROWSER_SUPPORT_MIME !== void 0 ? _BROWSER_SUPPORT_MIME : '';
  if (!browserSupportMimeType) {
    logger.error('VoiceRecorder: Browser does not support mimeType', {
      mimmeTypes: BROWSER_SUPPORT_MIME_TYPE_LIST
    });
  }
  const [webAudioUtils, setWebAudioUtils] = useState(null);
  useEffect(() => {
    if (isVoiceMessageEnabled && !webAudioUtils) {
      import('../WebAudioUtils-7c8d9b9c.js').then(data => {
        setWebAudioUtils(data);
      });
    }
  }, []);
  const start = useCallback(eventHandler => {
    var _navigator, _navigator$mediaDevic, _navigator$mediaDevic2;
    if (isVoiceMessageEnabled && !webAudioUtils) {
      logger.error('VoiceRecorder: Recording audio processor is being loaded.');
      return;
    }
    logger.info('VoiceRecorder: Start recording.');
    if (mediaRecorder) {
      stop();
      logger.info('VoiceRecorder: Previous mediaRecorder is stopped.');
    }
    checkPermission();
    (_navigator = navigator) === null || _navigator === void 0 ? void 0 : (_navigator$mediaDevic = _navigator.mediaDevices) === null || _navigator$mediaDevic === void 0 ? void 0 : (_navigator$mediaDevic2 = _navigator$mediaDevic.getUserMedia) === null || _navigator$mediaDevic2 === void 0 ? void 0 : _navigator$mediaDevic2.call(_navigator$mediaDevic, {
      audio: true
    }).then(stream => {
      logger.info('VoiceRecorder: Succeeded getting media stream.', stream);
      setIsRecordable(true);
      const mediaRecorder = new MediaRecorder(stream, {
        mimeType: browserSupportMimeType,
        audioBitsPerSecond: VOICE_RECORDER_AUDIO_BIT_RATE
      });
      mediaRecorder.ondataavailable = e => {
        var _stream$getAudioTrack, _stream$getAudioTrack2, _stream$getAudioTrack3;
        // when recording stops
        logger.info('VoiceRecorder: Succeeded getting an available data.', e.data);
        const audioFile = new File([e.data], VOICE_MESSAGE_FILE_NAME, {
          lastModified: new Date().getTime(),
          type: VOICE_MESSAGE_MIME_TYPE
        });
        webAudioUtils === null || webAudioUtils === void 0 ? void 0 : webAudioUtils.downsampleToWav(audioFile, buffer => {
          const mp3Buffer = webAudioUtils === null || webAudioUtils === void 0 ? void 0 : webAudioUtils.encodeMp3(buffer);
          const mp3blob = new Blob(mp3Buffer, {
            type: VOICE_MESSAGE_MIME_TYPE
          });
          const convertedAudioFile = new File([mp3blob], VOICE_MESSAGE_FILE_NAME, {
            lastModified: new Date().getTime(),
            type: VOICE_MESSAGE_MIME_TYPE
          });
          eventHandler === null || eventHandler === void 0 ? void 0 : eventHandler.onRecordingEnded(convertedAudioFile);
          logger.info('VoiceRecorder: Succeeded converting audio file.', convertedAudioFile);
        });
        stream === null || stream === void 0 ? void 0 : (_stream$getAudioTrack = stream.getAudioTracks) === null || _stream$getAudioTrack === void 0 ? void 0 : (_stream$getAudioTrack2 = (_stream$getAudioTrack3 = _stream$getAudioTrack.call(stream)).forEach) === null || _stream$getAudioTrack2 === void 0 ? void 0 : _stream$getAudioTrack2.call(_stream$getAudioTrack3, track => track === null || track === void 0 ? void 0 : track.stop());
        setIsRecordable(false);
      };
      mediaRecorder === null || mediaRecorder === void 0 ? void 0 : mediaRecorder.start();
      setMediaRecorder(mediaRecorder);
      eventHandler === null || eventHandler === void 0 ? void 0 : eventHandler.onRecordingStarted();
    }).catch(err => {
      logger.error('VoiceRecorder: Failed getting media stream.', err);
      setMediaRecorder(null);
    });
  }, [mediaRecorder, webAudioUtils]);
  const stop = useCallback(() => {
    // Stop recording
    mediaRecorder === null || mediaRecorder === void 0 ? void 0 : mediaRecorder.stop();
    setMediaRecorder(null);
    setIsRecordable(false);
    logger.info('VoiceRecorder: Stop recording.');
  }, [mediaRecorder]);
  return /*#__PURE__*/React__default.createElement(Context.Provider, {
    value: {
      start,
      stop,
      isRecordable
    }
  }, children, permissionWarning && /*#__PURE__*/React__default.createElement(Modal, {
    hideFooter: true,
    onCancel: () => setPermissionWarning(false)
  }, /*#__PURE__*/React__default.createElement(React__default.Fragment, null, stringSet.VOICE_RECORDING_PERMISSION_DENIED)));
};
const useVoiceRecorderContext = () => useContext(Context);
var index = {
  VoiceRecorderProvider,
  useVoiceRecorderContext
};

export { VoiceRecorderProvider, index as default, useVoiceRecorderContext };
//# sourceMappingURL=context.js.map
