import RecordRTC, { RecordRTCPromisesHandler, bytesToSize } from 'recordrtc';

import { FileTypes } from 'src/types/attachments';
import { getDownloadAudioName } from 'src/utils/attachments';

const initialSettings = {
  mimeType: 'audio/mp3',
  bitsPerSecond: 128000,
  bufferSize: 512,
  numberOfAudioChannels: 1,
  recorderType: RecordRTC.StereoAudioRecorder,
  desiredSampRate: 16000,
  timeSlice: 100,
};

export const getPermissionInitializeRecorder = async (
  recordingType: RecordRTC.Options['type'],
  setting = initialSettings,
) => {
  const stream = await navigator.mediaDevices.getUserMedia({
    audio: true,
    video: false,
  });
  const recorder = new RecordRTCPromisesHandler(stream, {
    type: recordingType,
    ...setting,
  });

  return { recorder, stream };
};

export const formatMinutes = minutes =>
  minutes < 10 ? `0${minutes}` : minutes;

export const formatSeconds = seconds =>
  seconds < 10 ? `0${seconds}` : seconds;

export const formatDurationAudio = (minutes, seconds) =>
  minutes * 60000 + seconds * 1000;

export const buildAudioRecord = (uri, duration, size, extension) => ({
  uri,
  mime: 'audio/mp3',
  type: FileTypes.AUDIO,
  name: `${getDownloadAudioName()}.${extension}`,
  size: bytesToSize(size),
  width: duration,
});

export const getExtension = uri =>
  uri.match(/[^:]\w+\/[\w-+\d.]+(?=;|,)/)[0].split('/')[1];
