'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var React = require('react');
var LocalizationContext = require('../LocalizationContext-8cc9717d.js');
var ui_Modal = require('../ui/Modal.js');
var consts = require('../consts-9641990e.js');
var useSendbirdStateContext = require('../useSendbirdStateContext.js');
require('../stringSet-ce782136.js');
require('../index-d749c4c2.js');
require('react-dom');
require('../index-8029e07a.js');
require('../ui/Button.js');
require('../index-35633fb6.js');
require('prop-types');
require('../ui/Icon.js');
require('../ui/IconButton.js');
require('../_rollupPluginBabelHelpers-acf412a3.js');
require('../MediaQueryContext-fad211ad.js');
require('../withSendbird.js');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var React__default = /*#__PURE__*/_interopDefaultLegacy(React);

// Input props of VoiceRecorder

// Output of VoiceRecorder

const noop = () => {/* noop */};
const Context = /*#__PURE__*/React.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] = React.useState(null);
  const [isRecordable, setIsRecordable] = React.useState(false);
  const [permissionWarning, setPermissionWarning] = React.useState(false);
  const {
    stringSet
  } = LocalizationContext.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 = consts.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: consts.BROWSER_SUPPORT_MIME_TYPE_LIST
    });
  }
  const [webAudioUtils, setWebAudioUtils] = React.useState(null);
  React.useEffect(() => {
    if (isVoiceMessageEnabled && !webAudioUtils) {
      Promise.resolve().then(function () { return require('../WebAudioUtils-b81ee971.js'); }).then(data => {
        setWebAudioUtils(data);
      });
    }
  }, []);
  const start = React.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: consts.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], consts.VOICE_MESSAGE_FILE_NAME, {
          lastModified: new Date().getTime(),
          type: consts.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: consts.VOICE_MESSAGE_MIME_TYPE
          });
          const convertedAudioFile = new File([mp3blob], consts.VOICE_MESSAGE_FILE_NAME, {
            lastModified: new Date().getTime(),
            type: consts.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 = React.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["default"].createElement(Context.Provider, {
    value: {
      start,
      stop,
      isRecordable
    }
  }, children, permissionWarning && /*#__PURE__*/React__default["default"].createElement(ui_Modal["default"], {
    hideFooter: true,
    onCancel: () => setPermissionWarning(false)
  }, /*#__PURE__*/React__default["default"].createElement(React__default["default"].Fragment, null, stringSet.VOICE_RECORDING_PERMISSION_DENIED)));
};
const useVoiceRecorderContext = () => React.useContext(Context);
var index = {
  VoiceRecorderProvider,
  useVoiceRecorderContext
};

exports.VoiceRecorderProvider = VoiceRecorderProvider;
exports["default"] = index;
exports.useVoiceRecorderContext = useVoiceRecorderContext;
//# sourceMappingURL=context.js.map
