function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
import React, { forwardRef, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import chatStore from './ChatStore';
import CameraRollPicker from '../../components/cameraRollPicker';
import { observer } from 'mobx-react-lite';
import { Log, requestPermission } from '../../utils';
import { Dimensions, FlatList, Image, Platform, TouchableOpacity, View } from 'react-native';
import { check, PERMISSIONS, RESULTS, request } from 'react-native-permissions';
import colors from '../../Styles';
import appStore from '../AppStore';
import AudioRecorderPlayer from '../../components/audioRecord/index';
import RNFS from 'react-native-fs';
import uuid from 'react-native-uuid';
import DocumentPicker, { types } from '../../components/documentPicker';
import { MText as Text } from '../../components';
import { AudioSourceAndroidType, AVEncoderAudioQualityIOSType, AVEncodingOption, AVModeIOSOption, AudioEncoderAndroidType } from "../../components/audioRecord/index.android";
import AnimatedSoundBars from "../../components/waveView";
export class RecordButton extends React.Component {
  constructor(props) {
    super(props);
    _defineProperty(this, "startRecord", async () => {
      try {
        requestPermission(Platform.OS === 'android' ? [PERMISSIONS.ANDROID.RECORD_AUDIO, PERMISSIONS.ANDROID.WRITE_EXTERNAL_STORAGE, PERMISSIONS.ANDROID.READ_EXTERNAL_STORAGE] : [PERMISSIONS.IOS.MICROPHONE], async () => {
          this.setState({
            actionRecord: true
          });
          const result = await this.audioRecorderPlayer.startRecorder(this.path, {
            AudioEncoderAndroid: AudioEncoderAndroidType.AAC,
            AudioSourceAndroid: AudioSourceAndroidType.MIC,
            AVModeIOS: AVModeIOSOption.measurement,
            AVEncoderAudioQualityKeyIOS: AVEncoderAudioQualityIOSType.high,
            AVNumberOfChannelsKeyIOS: 2,
            AVFormatIDKeyIOS: AVEncodingOption.aac
          });
          this.audioRecorderPlayer.addRecordBackListener(e => {
            this.setState({
              isRecording: Platform.OS === 'ios' ? e.current_position !== undefined : e.currentPosition !== undefined,
              recordSecs: e.currentPosition,
              recordTime: this.audioRecorderPlayer.mmssss(Math.floor(Platform.OS === 'ios' ? Number(e.current_position) : e.currentPosition))
            });
            return;
          });
        });
      } catch (e) {}
    });
    _defineProperty(this, "sendRecorded", async () => {
      try {
        const message = {
          id: uuid.v4(),
          type: 'VOICE',
          attachmentLocal: [{
            uri: this.state.fileRecorded,
            extension: 'mp3',
            name: uuid.v4() + '.mp3',
            duration: this.state.recordSecs / 1000
          }],
          has_attachment: true,
          text: '',
          status: 'sending',
          sender: appStore.user.type + '_' + appStore.user.user_id,
          conversation_id: this.props.data._id
        };
        chatStore.data = [message, ...chatStore.data];
        await chatStore.sendMessage(message);
        this.setState({
          isRecording: false,
          actionRecord: false,
          fileRecorded: undefined,
          recordSecs: 0,
          layout: {
            x: 0
          },
          recordTime: '00:00'
        });
      } catch (err) {
        console.warn(err);
      }
    });
    _defineProperty(this, "onStopRecord", async () => {
      try {
        try {
          this.soundbarRef.stop();
        } catch (e) {}
        const result = await this.audioRecorderPlayer.stopRecorder();
        this.audioRecorderPlayer.removeRecordBackListener();
        if (result && result.includes('file://')) {
          this.setState({
            isRecording: false,
            fileRecorded: result
          });
        } else {
          this.setState({
            isRecording: false,
            fileRecorded: undefined
          });
        }
      } catch (e) {}
    });
    _defineProperty(this, "onStartPlay", async () => {
      try {
        this.soundbarRef.play();
      } catch (e) {}
      const msg = await this.audioRecorderPlayer.startPlayer(this.state.fileRecorded);
      this.audioRecorderPlayer.addPlayBackListener(e => {
        this.setState({
          currentPositionSec: e.currentPosition,
          currentDurationSec: e.duration,
          playTime: this.audioRecorderPlayer.mmssss(Math.floor(e.currentPosition)),
          duration: this.audioRecorderPlayer.mmssss(Math.floor(e.duration))
        });
        return;
      });
    });
    _defineProperty(this, "onPausePlay", async () => {
      await this.audioRecorderPlayer.pausePlayer();
    });
    _defineProperty(this, "onStopPlay", async () => {
      this.audioRecorderPlayer.stopPlayer();
      this.audioRecorderPlayer.removePlayBackListener();
    });
    this.state = {
      fileRecorded: undefined,
      isRecording: false,
      actionRecord: false,
      isPlay: false,
      recordSecs: 0,
      layout: {
        x: 0
      },
      recordTime: '00:00'
    };
    this.path = Platform.select({
      ios: uuid.v4() + '.m4a',
      android: `${RNFS.CachesDirectoryPath}/${uuid.v4() + '.mp3'}`
    });
    this.audioRecorderPlayer = new AudioRecorderPlayer();
  }
  componentWillUnmount() {
    try {
      this.audioRecorderPlayer.stopRecorder();
      this.audioRecorderPlayer.removeRecordBackListener();
    } catch (e) {}
  }
  render() {
    var _this$state$layout;
    return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(TouchableOpacity, _extends({}, this.props, {
      onLayout: _ref => {
        let {
          nativeEvent
        } = _ref;
        this.setState({
          layout: nativeEvent
        });
      },
      onPress: () => {
        if (this.state.isRecording) {
          this.onStopRecord();
        } else {
          this.onStopRecord();
          this.startRecord();
        }
      },
      style: {
        width: 56,
        height: 56,
        alignItems: 'center',
        justifyContent: 'center'
      }
    }), this.props.children), this.state.actionRecord && /*#__PURE__*/React.createElement(View, {
      style: {
        flexDirection: 'row',
        alignItems: 'center',
        height: 56,
        width: '100%',
        backgroundColor: '#F8F8FA',
        position: 'absolute',
        top: (_this$state$layout = this.state.layout) === null || _this$state$layout === void 0 ? void 0 : _this$state$layout.x
      }
    }, /*#__PURE__*/React.createElement(TouchableOpacity, {
      onPress: async () => {
        try {
          try {
            this.onStopRecord();
          } catch (e) {
            console.log(e);
          }
          try {
            await RNFS.unlink(this.state.fileRecorded).then(() => {
              console.log('FILE DELETED');
            })
            // `unlink` will throw an error, if the item to unlink does not exist
            .catch(err => {});
          } catch (e) {
            console.log(e);
          }
          this.setState({
            fileRecorded: undefined,
            isRecording: false,
            actionRecord: false,
            recordSecs: 0,
            recordTime: '00:00'
          });
        } catch (e) {
          console.log(e);
        }
      },
      style: {
        width: 56,
        height: 56,
        alignItems: 'center',
        justifyContent: 'center'
      }
    }, /*#__PURE__*/React.createElement(Image, {
      source: require('../../assets/ic_trash_primary.png'),
      style: {
        height: 24,
        width: 24,
        resizeMode: 'contain'
      }
    })), /*#__PURE__*/React.createElement(View, {
      style: {
        width: 1,
        height: 28,
        backgroundColor: '#DCE6F0',
        marginVertical: 4
      }
    }), /*#__PURE__*/React.createElement(AnimatedSoundBars, {
      isPlay: true,
      barColor: colors.primary,
      length: 20
    }), /*#__PURE__*/React.createElement(View, {
      style: {
        width: 56,
        height: 56,
        alignItems: 'center',
        justifyContent: 'center'
      }
    }, /*#__PURE__*/React.createElement(Text, {
      style: {
        fontWeight: '500',
        fontSize: 15,
        color: colors.neutralText
      }
    }, this.state.recordTime)), /*#__PURE__*/React.createElement(TouchableOpacity, {
      onPress: async () => {
        await this.onStopRecord();
        if (this.state.fileRecorded && !this.state.isRecording) {
          this.sendRecorded();
          this.setState({
            isRecording: false,
            actionRecord: false
          });
        }
      },
      style: {
        width: 56,
        height: 56,
        alignItems: 'center',
        justifyContent: 'center'
      }
    }, this.state.isRecording && /*#__PURE__*/React.createElement(Image, {
      source: require('../../assets/ic_send.png'),
      style: {
        height: 24,
        width: 24,
        resizeMode: 'contain'
      }
    }))));
  }
}
//# sourceMappingURL=RecordButton.js.map