"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.RecordButton = void 0;
var _react = _interopRequireWildcard(require("react"));
var _ChatStore = _interopRequireDefault(require("./ChatStore"));
var _cameraRollPicker = _interopRequireDefault(require("../../components/cameraRollPicker"));
var _mobxReactLite = require("mobx-react-lite");
var _utils = require("../../utils");
var _reactNative = require("react-native");
var _reactNativePermissions = require("react-native-permissions");
var _Styles = _interopRequireDefault(require("../../Styles"));
var _AppStore = _interopRequireDefault(require("../AppStore"));
var _index = _interopRequireDefault(require("../../components/audioRecord/index"));
var _reactNativeFs = _interopRequireDefault(require("react-native-fs"));
var _reactNativeUuid = _interopRequireDefault(require("react-native-uuid"));
var _documentPicker = _interopRequireWildcard(require("../../components/documentPicker"));
var _components = require("../../components");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
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); }
class RecordButton extends _react.default.Component {
  constructor(props) {
    super(props);
    _defineProperty(this, "startRecord", async () => {
      try {
        (0, _utils.requestPermission)(_reactNative.Platform.OS === 'android' ? [_reactNativePermissions.PERMISSIONS.ANDROID.RECORD_AUDIO, _reactNativePermissions.PERMISSIONS.ANDROID.WRITE_EXTERNAL_STORAGE, _reactNativePermissions.PERMISSIONS.ANDROID.READ_EXTERNAL_STORAGE] : [_reactNativePermissions.PERMISSIONS.IOS.MICROPHONE], async () => {
          this.setState({
            actionRecord: true
          });
          const result = await this.audioRecorderPlayer.startRecorder(this.path);
          this.audioRecorderPlayer.addRecordBackListener(e => {
            this.setState({
              isRecording: _reactNative.Platform.OS === 'ios' ? e.current_position !== undefined : e.currentPosition !== undefined,
              recordSecs: e.currentPosition,
              recordTime: this.audioRecorderPlayer.mmssss(Math.floor(_reactNative.Platform.OS === 'ios' ? Number(e.current_position) : e.currentPosition))
            });
            return;
          });
        });
      } catch (e) {}
    });
    _defineProperty(this, "sendRecorded", async () => {
      try {
        const message = {
          id: _reactNativeUuid.default.v4(),
          type: 'VOICE',
          attachmentLocal: [{
            uri: this.state.fileRecorded,
            extension: 'mp3',
            name: _reactNativeUuid.default.v4() + '.mp3'
          }],
          has_attachment: true,
          text: '',
          status: 'sending',
          sender: _AppStore.default.user.type + '_' + _AppStore.default.user.user_id,
          conversation_id: this.props.data._id
        };
        _ChatStore.default.data.unshift(message);
        await _ChatStore.default.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 {
        const result = await this.audioRecorderPlayer.stopRecorder();
        this.audioRecorderPlayer.removeRecordBackListener();
        if (result && result.includes('file://')) {
          this.setState({
            isRecording: false,
            fileRecorded: result,
            recordSecs: 0
          });
        } else {
          this.setState({
            isRecording: false,
            fileRecorded: undefined,
            recordSecs: 0
          });
        }
      } catch (e) {}
    });
    _defineProperty(this, "onStartPlay", async () => {
      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 = _reactNative.Platform.select({
      ios: _reactNativeUuid.default.v4() + '.m4a',
      android: `${_reactNativeFs.default.CachesDirectoryPath}/${_reactNativeUuid.default.v4() + '.mp3'}`
    });
    this.audioRecorderPlayer = new _index.default();
  }
  componentWillUnmount() {
    try {
      this.audioRecorderPlayer.stopRecorder();
      this.audioRecorderPlayer.removeRecordBackListener();
    } catch (e) {}
  }
  render() {
    var _this$state$layout;
    return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_reactNative.TouchableOpacity, _extends({}, this.props, {
      onLayout: _ref => {
        let {
          nativeEvent
        } = _ref;
        this.setState({
          layout: nativeEvent
        });
      },
      onPress: () => {
        if (this.state.isRecording) {
          this.onStopRecord();
        } else {
          this.startRecord();
        }
      },
      style: {
        width: 56,
        height: 56,
        alignItems: 'center',
        justifyContent: 'center'
      }
    }), this.props.children), this.state.actionRecord && /*#__PURE__*/_react.default.createElement(_reactNative.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.default.createElement(_reactNative.TouchableOpacity, {
      onPress: async () => {
        try {
          try {
            this.onStopRecord();
          } catch (e) {
            console.log(e);
          }
          try {
            await _reactNativeFs.default.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.default.createElement(_reactNative.Image, {
      source: require('../../assets/ic_trash_primary.png'),
      style: {
        height: 24,
        width: 24,
        resizeMode: 'contain'
      }
    })), /*#__PURE__*/_react.default.createElement(_reactNative.Image, {
      source: require('../../assets/ic_wave.png'),
      style: {
        flex: 1,
        height: 32,
        resizeMode: 'contain'
      }
    }), /*#__PURE__*/_react.default.createElement(_reactNative.View, {
      style: {
        width: 56,
        height: 56,
        alignItems: 'center',
        justifyContent: 'center'
      }
    }, /*#__PURE__*/_react.default.createElement(_components.MText, {
      style: {
        fontWeight: '500',
        fontSize: 15,
        color: _Styles.default.neutralText
      }
    }, this.state.recordTime)), /*#__PURE__*/_react.default.createElement(_reactNative.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.default.createElement(_reactNative.Image, {
      source: require('../../assets/ic_send.png'),
      style: {
        height: 24,
        width: 24,
        resizeMode: 'contain'
      }
    }))));
  }
}
exports.RecordButton = RecordButton;
//# sourceMappingURL=RecordButton.js.map