"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _reactNative = require("react-native");
var _react = require("react");
var _reactNativeVisionCamera = require("react-native-vision-camera");
var _styles = require("./styles");
var _reactNativeSvg = require("react-native-svg");
var _xml = require("../../../../core/assets/icons/xml");
var _reactNativeImagePicker = require("react-native-image-picker");
var Progress = _interopRequireWildcard(require("react-native-progress"));
var _time = require("../../../../core/utils/time");
var _enums = require("../../../enums");
var _native = require("@react-navigation/native");
var _Draft = _interopRequireDefault(require("../Draft"));
var _url = require("../../../../core/utils/url");
var _reactNativeSafeAreaContext = require("react-native-safe-area-context");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
var ACTIVE_SWITCH = /*#__PURE__*/function (ACTIVE_SWITCH) {
  ACTIVE_SWITCH["camera"] = "camera";
  ACTIVE_SWITCH["video"] = "video";
  return ACTIVE_SWITCH;
}(ACTIVE_SWITCH || {});
const AmityCreateStoryPage = ({
  targetId,
  targetType,
  onCreateStory,
  onDiscardStory
}) => {
  const {
    hasPermission: hasCameraPermission
  } = (0, _reactNativeVisionCamera.useCameraPermission)();
  const {
    hasPermission: hasMicrophonePermission
  } = (0, _reactNativeVisionCamera.useMicrophonePermission)();
  const [cameraKey, setCameraKey] = (0, _react.useState)(0);
  const {
    width,
    height
  } = (0, _reactNative.useWindowDimensions)();
  const isPortrait = width < height;
  const landscapeStyle = !isPortrait && {
    transform: [{
      rotate: '-90deg'
    }],
    height: width - 100,
    alignSelf: 'center'
  };
  const navigation = (0, _native.useNavigation)();
  const styles = (0, _styles.useStyles)();
  const backCamera = (0, _reactNativeVisionCamera.useCameraDevice)('back');
  const frontCamera = (0, _reactNativeVisionCamera.useCameraDevice)('front');
  const cameraRef = (0, _react.useRef)(null);
  const timerRef = (0, _react.useRef)(undefined);
  const [activeSwitch, setActiveSwitch] = (0, _react.useState)(ACTIVE_SWITCH.camera);
  const isCamera = activeSwitch === ACTIVE_SWITCH.camera;
  const isVideo = activeSwitch === ACTIVE_SWITCH.video;
  const [flashOnState, setFlashOnState] = (0, _react.useState)(false);
  const [activeCamera, setActiveCamera] = (0, _react.useState)(backCamera);
  const [isRecording, setIsRecording] = (0, _react.useState)(false);
  const [showDraftStory, setShowDraftStory] = (0, _react.useState)(false);
  const [mediaTypeData, setMediaTypeData] = (0, _react.useState)(null);
  const format = _reactNative.Platform.select({
    ios: (0, _reactNativeVisionCamera.useCameraFormat)(activeCamera, [{
      photoAspectRatio: 16 / 9
    }, {
      videoAspectRatio: 16 / 9
    }]),
    android: (0, _reactNativeVisionCamera.useCameraFormat)(activeCamera, [{
      photoAspectRatio: 16 / 9
    }, {
      videoAspectRatio: 16 / 9
    }])
  });
  const activeSwitchColor = {
    backgroundColor: '#ffffff'
  };
  const [totalTime, setTotalTime] = (0, _react.useState)(0);
  const [timer, setTimer] = (0, _react.useState)('');
  const TIMER_LIMIT = 60000;
  const timerBgColor = (isRecording || totalTime > 0) && {
    backgroundColor: '#FF305A'
  };
  const onStopRecord = (0, _react.useCallback)(() => {
    var _cameraRef$current;
    setIsRecording(false);
    clearInterval(timerRef === null || timerRef === void 0 ? void 0 : timerRef.current);
    cameraRef === null || cameraRef === void 0 || (_cameraRef$current = cameraRef.current) === null || _cameraRef$current === void 0 || _cameraRef$current.stopRecording();
  }, []);
  (0, _react.useEffect)(() => {
    if (backCamera && !activeCamera) {
      setActiveCamera(backCamera);
    }
  }, [backCamera, activeCamera]);
  (0, _react.useEffect)(() => {
    if (hasCameraPermission && hasMicrophonePermission && activeCamera) {
      // Force remount camera component
      setCameraKey(prev => prev + 1);
    }
  }, [hasCameraPermission, hasMicrophonePermission, activeCamera]);
  (0, _react.useEffect)(() => {
    if (totalTime === TIMER_LIMIT) return onStopRecord();
    if (!isRecording) return clearInterval(timerRef === null || timerRef === void 0 ? void 0 : timerRef.current);
    timerRef.current = setInterval(() => setTotalTime(prev => prev + 100), 100);
    return () => clearInterval(timerRef === null || timerRef === void 0 ? void 0 : timerRef.current);
  }, [isRecording, onStopRecord, totalTime]);
  (0, _react.useEffect)(() => {
    if (totalTime % 1000 === 0) {
      const timerString = (0, _time.msToString)(totalTime);
      setTimer(timerString);
    }
  }, [totalTime]);
  const onPressCamera = (0, _react.useCallback)(() => {
    setActiveSwitch(ACTIVE_SWITCH.camera);
  }, []);
  const onPressVideo = (0, _react.useCallback)(() => {
    setActiveSwitch(ACTIVE_SWITCH.video);
  }, []);
  const onFinishCapture = (0, _react.useCallback)(cameraData => {
    setTotalTime(0);
    if (!cameraData) return _reactNative.Alert.alert('Error', 'Error on camera, please try again');
    const name = cameraData.path.split('/').pop();
    const uri = _reactNative.Platform.select({
      ios: cameraData.path,
      android: `file://${cameraData.path}`
    });
    const type = (0, _url.getMediaTypeFromUrl)(uri);
    if (!type) {
      _reactNative.Alert.alert('Error', 'Unsupported Media Format');
      return;
    }
    const data = {
      ...cameraData,
      uri: uri,
      name: name
    };
    setMediaTypeData(data);
    setShowDraftStory(true);
  }, []);
  const onPressCameraCapture = (0, _react.useCallback)(async () => {
    var _cameraRef$current2;
    const photo = await (cameraRef === null || cameraRef === void 0 || (_cameraRef$current2 = cameraRef.current) === null || _cameraRef$current2 === void 0 ? void 0 : _cameraRef$current2.takePhoto({
      flash: flashOnState ? 'on' : 'off',
      enableShutterSound: false
    }));
    onFinishCapture(photo);
  }, [flashOnState, onFinishCapture]);
  const onStartRecord = (0, _react.useCallback)(() => {
    var _cameraRef$current3;
    setIsRecording(true);
    cameraRef === null || cameraRef === void 0 || (_cameraRef$current3 = cameraRef.current) === null || _cameraRef$current3 === void 0 || _cameraRef$current3.startRecording({
      onRecordingFinished: video => onFinishCapture(video),
      onRecordingError: error => {
        if (error.message.includes('no data was received! (null)')) {
          _reactNative.Alert.alert('Video Too Short', 'Please press and hold the button for at least 1 second to record a video.');
        } else _reactNative.Alert.alert('Video Record Error', error.message);
      },
      fileType: 'mp4',
      flash: flashOnState ? 'on' : 'off'
    });
  }, [flashOnState, onFinishCapture]);
  const renderCaptureBtn = (0, _react.useCallback)(() => {
    if (isCamera) {
      return /*#__PURE__*/React.createElement(_reactNative.Pressable, {
        style: styles.cameraCaptureBtn,
        onPress: onPressCameraCapture
      }, /*#__PURE__*/React.createElement(_reactNative.View, {
        style: styles.cameraCaptureBtnFill
      }));
    }
    return /*#__PURE__*/React.createElement(_reactNative.Pressable, {
      style: styles.videoCaptureBtn,
      onPressIn: onStartRecord,
      onPressOut: onStopRecord
    }, /*#__PURE__*/React.createElement(_reactNative.View, {
      style: [styles.videoCaptureInnerButton, !isRecording && {
        width: 62,
        height: 62,
        borderRadius: 100
      }]
    }, /*#__PURE__*/React.createElement(Progress.Circle, {
      size: 75,
      progress: totalTime / TIMER_LIMIT,
      borderColor: "transparent",
      color: "red"
    })));
  }, [isCamera, onPressCameraCapture, onStartRecord, onStopRecord, styles, totalTime, isRecording]);
  const onPressBack = (0, _react.useCallback)(() => {
    navigation.goBack();
  }, [navigation]);
  const onPressFlash = (0, _react.useCallback)(() => {
    setFlashOnState(prev => !prev);
  }, []);
  const onPressSwitch = (0, _react.useCallback)(() => {
    setActiveCamera(prev => prev === backCamera ? frontCamera : backCamera);
  }, [backCamera, frontCamera]);
  const onPressGallery = (0, _react.useCallback)(async () => {
    const type = isCamera ? 'photo' : _enums.StoryType.video;
    const result = await (0, _reactNativeImagePicker.launchImageLibrary)({
      mediaType: type,
      quality: 1,
      selectionLimit: 1
    });
    if (!result.didCancel && result.assets && result.assets.length > 0) {
      const data = {
        ...result.assets[0],
        path: result.assets[0].uri
      };
      if (data) {
        onFinishCapture(data);
      } else {
        _reactNative.Alert.alert('Error on media selection');
      }
    }
  }, [isCamera, onFinishCapture]);
  if (!activeCamera) return null;
  return /*#__PURE__*/React.createElement(_reactNativeSafeAreaContext.SafeAreaView, {
    style: styles.wrapper
  }, /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.cameraContainer
  }, /*#__PURE__*/React.createElement(_reactNativeVisionCamera.Camera, {
    ref: cameraRef,
    key: cameraKey,
    style: [styles.camera, landscapeStyle],
    device: activeCamera,
    isActive: true,
    video: isVideo,
    photo: isCamera,
    audio: true,
    format: format,
    outputOrientation: "device"
  }), renderCaptureBtn(), isVideo && /*#__PURE__*/React.createElement(_reactNative.View, {
    style: [styles.timer, timerBgColor]
  }, /*#__PURE__*/React.createElement(_reactNative.Text, {
    style: styles.timerTxt
  }, timer)), /*#__PURE__*/React.createElement(_reactNative.TouchableOpacity, {
    style: styles.backBtn,
    onPress: onPressBack
  }, /*#__PURE__*/React.createElement(_reactNativeSvg.SvgXml, {
    xml: (0, _xml.closeIcon)('#fff'),
    width: 10,
    height: 10
  })), /*#__PURE__*/React.createElement(_reactNative.TouchableOpacity, {
    style: styles.flashIcon,
    onPress: onPressFlash
  }, /*#__PURE__*/React.createElement(_reactNativeSvg.SvgXml, {
    xml: flashOnState ? (0, _xml.flashOn)() : (0, _xml.flashOff)(),
    width: 24,
    height: 24
  })), /*#__PURE__*/React.createElement(_reactNative.TouchableOpacity, {
    style: styles.switchCamera,
    onPress: onPressSwitch
  }, /*#__PURE__*/React.createElement(_reactNativeSvg.SvgXml, {
    xml: (0, _xml.switchCamera)(),
    width: 32,
    height: 32
  })), /*#__PURE__*/React.createElement(_reactNative.TouchableOpacity, {
    style: styles.gallery,
    onPress: onPressGallery
  }, /*#__PURE__*/React.createElement(_reactNativeSvg.SvgXml, {
    xml: (0, _xml.storyGallery)(),
    width: 32,
    height: 32
  }))), /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.switchContainer
  }, /*#__PURE__*/React.createElement(_reactNative.Pressable, {
    style: [styles.switch, isCamera && activeSwitchColor],
    onPress: onPressCamera
  }, /*#__PURE__*/React.createElement(_reactNative.Text, {
    style: styles.switchTxt
  }, "Photo")), /*#__PURE__*/React.createElement(_reactNative.Pressable, {
    style: [styles.switch, isVideo && activeSwitchColor],
    onPress: onPressVideo
  }, /*#__PURE__*/React.createElement(_reactNative.Text, {
    style: styles.switchTxt
  }, "Video"))), /*#__PURE__*/React.createElement(_reactNative.Modal, {
    visible: showDraftStory,
    animationType: "slide",
    onRequestClose: () => setShowDraftStory(false)
  }, /*#__PURE__*/React.createElement(_Draft.default, {
    targetId: targetId,
    targetType: targetType,
    mediaType: mediaTypeData,
    onCreateStory: () => {
      setShowDraftStory(false);
      onCreateStory();
    },
    onDiscardStory: () => {
      setShowDraftStory(false);
      onDiscardStory && onDiscardStory();
    }
  })));
};
var _default = exports.default = /*#__PURE__*/(0, _react.memo)(AmityCreateStoryPage);
//# sourceMappingURL=Create.js.map