import React__default, { useReducer, useContext, createContext } from 'react';
import { _ as _objectSpread2 } from './_rollupPluginBabelHelpers-a69fd1ce.js';
import { f as VOICE_PLAYER_ROOT_ID, g as VOICE_PLAYER_AUDIO_ID, b as VOICE_MESSAGE_FILE_NAME, c as VOICE_MESSAGE_MIME_TYPE } from './consts-e64103c6.js';
import useSendbirdStateContext from './useSendbirdStateContext.js';

const INITIALIZE_AUDIO_UNIT = 'INITIALIZE_AUDIO_UNIT';
const SET_CURRENT_PLAYER = 'SET_CURRENT_PLAYER';
const ON_VOICE_PLAYER_PLAY = 'ON_VOICE_PLAYER_PLAY';
const ON_VOICE_PLAYER_PAUSE = 'ON_VOICE_PLAYER_PAUSE';
const ON_CURRENT_TIME_UPDATE = 'ON_CURRENT_TIME_UPDATE';

const VOICE_PLAYER_STATUS = {
  IDLE: 'IDLE',
  PREPARING: 'PREPARING',
  PLAYING: 'PLAYING',
  PAUSED: 'PAUSED',
  COMPLETED: 'COMPLETED'
};
const AudioUnitDefaultValue = () => ({
  audioFile: null,
  playbackTime: 0,
  duration: 1000,
  playingStatus: VOICE_PLAYER_STATUS.IDLE
});
const voicePlayerInitialState = {
  currentPlayer: null,
  currentGroupKey: '',
  audioStorage: {}
};

function voicePlayerReducer(state, action) {
  switch (action.type) {
    case INITIALIZE_AUDIO_UNIT:
      {
        var _state$audioStorage;
        const {
          groupKey
        } = action.payload;
        const audioUnit = (_state$audioStorage = state.audioStorage) !== null && _state$audioStorage !== void 0 && _state$audioStorage[groupKey] ? state.audioStorage[groupKey] : AudioUnitDefaultValue();
        audioUnit.playingStatus = VOICE_PLAYER_STATUS.PREPARING;
        return _objectSpread2(_objectSpread2({}, state), {}, {
          audioStorage: _objectSpread2(_objectSpread2({}, state.audioStorage), {}, {
            [groupKey]: audioUnit
          })
        });
      }
    case SET_CURRENT_PLAYER:
      {
        const {
          audioPlayer,
          groupKey
        } = action.payload;
        return _objectSpread2(_objectSpread2({}, state), {}, {
          currentPlayer: audioPlayer,
          currentGroupKey: groupKey
        });
      }
    case ON_VOICE_PLAYER_PLAY:
      {
        var _state$audioStorage2;
        const {
          groupKey,
          audioFile
        } = action.payload;
        const audioUnit = (_state$audioStorage2 = state.audioStorage) !== null && _state$audioStorage2 !== void 0 && _state$audioStorage2[groupKey] ? state.audioStorage[groupKey] : AudioUnitDefaultValue();
        audioUnit.audioFile = audioFile;
        audioUnit.playingStatus = VOICE_PLAYER_STATUS.PLAYING;
        return _objectSpread2(_objectSpread2({}, state), {}, {
          audioStorage: _objectSpread2(_objectSpread2({}, state.audioStorage), {}, {
            [groupKey]: audioUnit
          })
        });
      }
    case ON_VOICE_PLAYER_PAUSE:
      {
        var _state$audioStorage3;
        const {
          groupKey
        } = action.payload;
        const audioUnit = (_state$audioStorage3 = state.audioStorage) !== null && _state$audioStorage3 !== void 0 && _state$audioStorage3[groupKey] ? state.audioStorage[groupKey] : AudioUnitDefaultValue();
        audioUnit.playingStatus = VOICE_PLAYER_STATUS.PAUSED;
        const {
          currentTime,
          duration
        } = state.currentPlayer;
        if (audioUnit.playbackTime === audioUnit.duration) {
          audioUnit.playbackTime = 0;
        } else if (currentTime > 0 && duration > 0) {
          audioUnit.playbackTime = currentTime;
          audioUnit.duration = duration;
        }
        return _objectSpread2(_objectSpread2({}, state), {}, {
          audioStorage: _objectSpread2(_objectSpread2({}, state.audioStorage), {}, {
            [groupKey]: audioUnit
          })
        });
      }
    case ON_CURRENT_TIME_UPDATE:
      {
        var _state$audioStorage4;
        const {
          groupKey
        } = action.payload;
        const {
          currentTime,
          duration
        } = state.currentPlayer;
        const audioUnit = (_state$audioStorage4 = state.audioStorage) !== null && _state$audioStorage4 !== void 0 && _state$audioStorage4[groupKey] ? state.audioStorage[groupKey] : AudioUnitDefaultValue();
        if (currentTime > 0 && duration > 0) {
          audioUnit.playbackTime = currentTime;
          audioUnit.duration = duration;
        }
        return _objectSpread2(_objectSpread2({}, state), {}, {
          audioStorage: _objectSpread2(_objectSpread2({}, state.audioStorage), {}, {
            [groupKey]: audioUnit
          })
        });
      }
    default:
      return state;
  }
}

// VoicePlayerProvider interface

const ALL = 'ALL';
const noop = () => {/* noop */};
const VoicePlayerStoreDefaultValue = {
  currentGroupKey: '',
  currentPlayer: null,
  audioStorage: {}
};
const Context = /*#__PURE__*/createContext({
  play: noop,
  pause: noop,
  stop: noop,
  voicePlayerStore: VoicePlayerStoreDefaultValue
});
const VoicePlayerProvider = _ref => {
  let {
    children
  } = _ref;
  const [voicePlayerStore, voicePlayerDispatcher] = useReducer(voicePlayerReducer, voicePlayerInitialState);
  const {
    currentGroupKey,
    currentPlayer,
    audioStorage
  } = voicePlayerStore;
  const {
    config
  } = useSendbirdStateContext();
  const {
    logger
  } = config;
  const stop = function () {
    let text = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
    if (currentGroupKey.includes(text)) {
      logger.info('VoicePlayer: Pause playing(by text).');
      pause(currentGroupKey);
    }
  };
  const pause = groupKey => {
    if (currentGroupKey === groupKey && currentPlayer !== null) {
      logger.info('VoicePlayer: Pause playing(by group key).');
      currentPlayer === null || currentPlayer === void 0 ? void 0 : currentPlayer.pause();
    }
    if (groupKey === ALL) {
      logger.info('VoicePlayer: Pause playing(all).');
      currentPlayer === null || currentPlayer === void 0 ? void 0 : currentPlayer.pause();
    }
  };
  const play = _ref2 => {
    let {
      groupKey,
      audioFile = null,
      audioFileUrl = ''
    } = _ref2;
    if (groupKey !== currentGroupKey) {
      pause(currentGroupKey);
    }

    // Clear the previous AudioPlayer element
    const voicePlayerRoot = document.getElementById(VOICE_PLAYER_ROOT_ID);
    const voicePlayerAudioElement = document.getElementById(VOICE_PLAYER_AUDIO_ID);
    if (voicePlayerAudioElement) {
      voicePlayerRoot.removeChild(voicePlayerAudioElement);
    }
    logger.info('VoicePlayer: Start getting audio file.');
    new Promise(resolve => {
      var _audioStorage$groupKe;
      voicePlayerDispatcher({
        type: INITIALIZE_AUDIO_UNIT,
        payload: {
          groupKey
        }
      });
      // audio file passed as a parameter
      if (audioFile) {
        logger.info('VoicePlayer: Use the audioFile instance.');
        resolve(audioFile);
        return;
      }
      // audio file from the audioStorage
      const cachedAudioFile = audioStorage === null || audioStorage === void 0 ? void 0 : (_audioStorage$groupKe = audioStorage[groupKey]) === null || _audioStorage$groupKe === void 0 ? void 0 : _audioStorage$groupKe.audioFile;
      if (cachedAudioFile) {
        logger.info('VoicePlayer: Get from the audioStorage.');
        resolve(cachedAudioFile);
        return;
      }
      // fetch the audio file from URL
      fetch(audioFileUrl).then(res => res.blob()).then(blob => {
        const audioFile = new File([blob], VOICE_MESSAGE_FILE_NAME, {
          lastModified: new Date().getTime(),
          type: VOICE_MESSAGE_MIME_TYPE
        });
        resolve(audioFile);
        logger.info('VoicePlayer: Get the audioFile from URL.');
      });
    }).then(audioFile => {
      var _URL, _URL$createObjectURL;
      const voicePlayerRoot = document.getElementById(VOICE_PLAYER_ROOT_ID);
      logger.info('VoicePlayer: Succeeded getting audio file.', {
        audioFile
      });
      const currentAudioUnit = audioStorage[groupKey] || AudioUnitDefaultValue();
      const audioPlayer = new Audio((_URL = URL) === null || _URL === void 0 ? void 0 : (_URL$createObjectURL = _URL.createObjectURL) === null || _URL$createObjectURL === void 0 ? void 0 : _URL$createObjectURL.call(_URL, audioFile));
      audioPlayer.id = VOICE_PLAYER_AUDIO_ID;
      audioPlayer.currentTime = currentAudioUnit.playbackTime;
      audioPlayer.volume = 1;
      audioPlayer.loop = false;
      audioPlayer.onplaying = () => {
        logger.info('VoicePlayer: OnPlaying event is called from audioPlayer', {
          groupKey,
          audioPlayer
        });
        voicePlayerDispatcher({
          type: ON_VOICE_PLAYER_PLAY,
          payload: {
            groupKey,
            audioFile
          }
        });
      };
      audioPlayer.onpause = () => {
        logger.info('VoicePlayer: OnPause event is called from audioPlayer', {
          groupKey,
          audioPlayer
        });
        voicePlayerDispatcher({
          type: ON_VOICE_PLAYER_PAUSE,
          payload: {
            groupKey
          }
        });
      };
      audioPlayer.ontimeupdate = () => {
        voicePlayerDispatcher({
          type: ON_CURRENT_TIME_UPDATE,
          payload: {
            groupKey
          }
        });
      };
      audioPlayer.dataset.sbGroupId = groupKey;
      // clean up the previous audio player
      try {
        voicePlayerRoot === null || voicePlayerRoot === void 0 ? void 0 : voicePlayerRoot.childNodes.forEach(node => {
          var _element$dataset;
          const element = node;
          const thisGroupKey = (_element$dataset = element.dataset) === null || _element$dataset === void 0 ? void 0 : _element$dataset.sbGroupKey;
          if (thisGroupKey !== groupKey) {
            var _element$pause;
            element === null || element === void 0 ? void 0 : (_element$pause = element.pause) === null || _element$pause === void 0 ? void 0 : _element$pause.call(element);
            voicePlayerDispatcher({
              type: ON_VOICE_PLAYER_PAUSE,
              payload: {
                groupKey
              }
            });
            voicePlayerRoot.removeChild(element);
            logger.info('VoicePlayer: Removed other player.', {
              element
            });
          }
        });
      } finally {
        audioPlayer === null || audioPlayer === void 0 ? void 0 : audioPlayer.play();
        voicePlayerRoot === null || voicePlayerRoot === void 0 ? void 0 : voicePlayerRoot.appendChild(audioPlayer);
        voicePlayerDispatcher({
          type: SET_CURRENT_PLAYER,
          payload: {
            groupKey,
            audioPlayer
          }
        });
        logger.info('VoicePlayer: Succeeded playing audio player.', {
          groupKey,
          audioPlayer
        });
      }
    });
  };
  return /*#__PURE__*/React__default.createElement(Context.Provider, {
    value: {
      play,
      pause,
      stop,
      voicePlayerStore
    }
  }, /*#__PURE__*/React__default.createElement("div", {
    id: VOICE_PLAYER_ROOT_ID,
    style: {
      display: 'none'
    }
  }), children);
};
const useVoicePlayerContext = () => useContext(Context);

export { ALL as A, VoicePlayerProvider as V, VOICE_PLAYER_STATUS as a, AudioUnitDefaultValue as b, useVoicePlayerContext as u };
//# sourceMappingURL=index-52ba73b9.js.map
