"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _react = _interopRequireWildcard(require("react"));
var _reactNative = require("react-native");
var _reactNativeCloudCa = require("react-native-cloud-ca");
var _styles = _interopRequireDefault(require("./styles"));
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); }
const MAX_LENGTH_OTP = 6;
const DeviceRegistrationView = props => {
  const {
    buttonLabel,
    onDone,
    children,
    registerDeviceParams,
    buttonLabelStyle,
    ...rest
  } = props;
  const cloudCAProviderContext = _react.default.useContext(_reactNativeCloudCa.CloudCAProviderContext);
  const {
    themeColor
  } = cloudCAProviderContext;
  const [isShowRequestRegister, setIsShowRequestRegister] = (0, _react.useState)(false);
  const [isShowError, setIsShowError] = (0, _react.useState)(false);
  const [isShowSuccess, setIsShowSuccess] = (0, _react.useState)(false);
  const [isShowOtp, setIsShowOtp] = (0, _react.useState)(false);
  const [isLoading, setIsLoading] = (0, _react.useState)(false);
  const [errorResponse, setErrorResponse] = (0, _react.useState)('');
  const [successResponse, setSuccessResponse] = (0, _react.useState)('');
  const [otpSms, setOtpSms] = (0, _react.useState)('');
  const [otpTimeLeft, setOtpTimeLeft] = _react.default.useState(0);
  const [allResult, setAllResult] = (0, _react.useState)();
  const [isOtpError, setIsOtpError] = (0, _react.useState)(false);
  _react.default.useEffect(() => {
    if (otpTimeLeft === 0) return;
    const intervalId = setInterval(() => {
      setOtpTimeLeft(prevTime => prevTime > 0 ? prevTime - 1 : 0);
    }, 1000);
    return () => clearInterval(intervalId);
  }, [otpTimeLeft]);
  const handleShowRequestRegister = state => {
    setIsShowRequestRegister(state);
  };
  const onRegister = async () => {
    setIsLoading(true);
    try {
      const authenticateClientResult = await (0, _reactNativeCloudCa.authenticateClient)();
      setAllResult({
        ...allResult,
        authenticateClientResponse: authenticateClientResult
      });
      await getOtp();
      handleShowRequestRegister(false);
      setIsLoading(false);
    } catch (error) {
      setIsOtpError(false);
      setAllResult({
        ...allResult,
        error: error
      });
      setErrorResponse(`${error === null || error === void 0 ? void 0 : error.code} - ${error === null || error === void 0 ? void 0 : error.message}`);
      handleShowRequestRegister(false);
      setIsShowError(true);
      setIsLoading(false);
    }
  };
  const getOtp = async () => {
    try {
      const authenticateUserResult = await (0, _reactNativeCloudCa.authenticateUser)();
      if ((authenticateUserResult === null || authenticateUserResult === void 0 ? void 0 : authenticateUserResult.auth_type) === 'OTP') {
        setOtpTimeLeft(120);
        setIsShowOtp(true);
      }
      setAllResult({
        ...allResult,
        authenticateUserResponse: authenticateUserResult
      });
    } catch (error) {
      setIsOtpError(false);
      setAllResult({
        ...allResult,
        error: error
      });
      setErrorResponse(`${error === null || error === void 0 ? void 0 : error.code} - ${error === null || error === void 0 ? void 0 : error.message}`);
      setIsShowError(true);
    }
  };
  const onConfirmOtp = async () => {
    try {
      const otpResult = await (0, _reactNativeCloudCa.verifyOTP)({
        otpSms: otpSms,
        otpMail: '',
        biometricApiType: registerDeviceParams === null || registerDeviceParams === void 0 ? void 0 : registerDeviceParams.biometricApiType
      });
      setOtpSms('');
      setIsShowOtp(false);
      if (_reactNative.Platform.OS === 'android') {
        setSuccessResponse('Đã đăng ký thiết bị thành công');
        setIsShowSuccess(true);
        const androidOtpResult = otpResult;
        setAllResult({
          ...allResult,
          registerDeviceResponse: androidOtpResult === null || androidOtpResult === void 0 ? void 0 : androidOtpResult.registerDeviceResponse,
          verifyOTPResponse: androidOtpResult === null || androidOtpResult === void 0 ? void 0 : androidOtpResult.verifyOTPResponse
        });
      } else {
        setAllResult({
          ...allResult,
          verifyOTPResponse: otpResult
        });
        await onRegisterDevices();
      }
    } catch (error) {
      setIsOtpError(true);
      setOtpSms('');
      setAllResult({
        ...allResult,
        error: error
      });
      setErrorResponse(`${error === null || error === void 0 ? void 0 : error.code} - ${error === null || error === void 0 ? void 0 : error.message}`);
      setIsShowError(true);
      setIsShowOtp(false);
    }
  };
  const onRegisterDevices = async () => {
    setIsLoading(true);
    try {
      const result = await (0, _reactNativeCloudCa.registerDevice)(registerDeviceParams);
      setSuccessResponse('Đã đăng ký thiết bị thành công');
      setIsShowSuccess(true);
      setAllResult({
        ...allResult,
        registerDeviceResponse: result
      });
      setIsLoading(false);
    } catch (error) {
      setIsLoading(false);
      setIsOtpError(false);
      setAllResult({
        ...allResult,
        error: error
      });
      setErrorResponse(`${error === null || error === void 0 ? void 0 : error.code} - ${error === null || error === void 0 ? void 0 : error.message}`);
      setIsShowError(true);
    }
  };
  const handleDone = () => {
    setIsShowSuccess(false);
    onDone === null || onDone === void 0 ? void 0 : onDone(allResult);
  };
  const handleError = () => {
    setIsShowError(false);
    if (isOtpError) {
      setIsOtpError(false);
      setIsShowOtp(true);
    }
    onDone === null || onDone === void 0 ? void 0 : onDone(allResult);
  };
  const renderChildren = () => {
    return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, children ? children : /*#__PURE__*/_react.default.createElement(_reactNative.Text, {
      style: buttonLabelStyle
    }, buttonLabel));
  };
  return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_reactNative.TouchableOpacity, _extends({
    onPress: () => handleShowRequestRegister(true)
  }, rest), renderChildren()), isLoading && /*#__PURE__*/_react.default.createElement(_reactNativeCloudCa.Loading, null), /*#__PURE__*/_react.default.createElement(_reactNativeCloudCa.Dialogue, {
    visible: isShowSuccess,
    onClose: handleDone
  }, /*#__PURE__*/_react.default.createElement(_reactNative.Text, {
    style: _styles.default.contentStyle
  }, successResponse)), /*#__PURE__*/_react.default.createElement(_reactNativeCloudCa.Dialogue, {
    modalType: "ERROR",
    onClose: handleError,
    visible: isShowError,
    animationType: isOtpError ? 'none' : 'fade'
  }, /*#__PURE__*/_react.default.createElement(_reactNative.Text, {
    style: _styles.default.contentStyle
  }, errorResponse)), /*#__PURE__*/_react.default.createElement(_reactNativeCloudCa.DialogueConfirm, {
    title: "\u0110\u0103ng k\xFD thi\u1EBFt b\u1ECB",
    closeOnPress: () => handleShowRequestRegister(false),
    closeLabel: "B\u1ECF qua",
    confirmOnPress: onRegister,
    confirmLabel: "Ti\u1EBFp t\u1EE5c",
    confirmDisable: isLoading,
    visible: isShowRequestRegister
  }, /*#__PURE__*/_react.default.createElement(_reactNative.Text, {
    style: _styles.default.contentStyle
  }, "B\u1EA1n c\xF3 mu\u1ED1n \u0111\u0103ng k\xFD thi\u1EBFt b\u1ECB n\xE0y \u0111\u1EC3 u\u1EF7 quy\u1EC1n t\u1EEB xa?")), /*#__PURE__*/_react.default.createElement(_reactNativeCloudCa.DialogueConfirm, {
    title: "X\xE1c th\u1EF1c ng\u01B0\u1EDDi d\xF9ng",
    animationType: isOtpError ? 'none' : 'fade',
    visible: isShowOtp,
    closeLabel: "B\u1ECF qua",
    closeOnPress: () => {
      setOtpSms('');
      setIsShowOtp(false);
    },
    confirmLabel: "Ti\u1EBFp t\u1EE5c",
    confirmOnPress: onConfirmOtp,
    confirmDisable: (otpSms === null || otpSms === void 0 ? void 0 : otpSms.length) < MAX_LENGTH_OTP || isLoading
  }, /*#__PURE__*/_react.default.createElement(_reactNative.Text, {
    style: _styles.default.contentStyle
  }, "Nh\u1EADp m\xE3 x\xE1c th\u1EF1c \u0111\u01B0\u1EE3c g\u1EEDi v\u1EC1 s\u1ED1 \u0111i\u1EC7n tho\u1EA1i \u0111\xE3 \u0111\u0103ng k\xFD"), /*#__PURE__*/_react.default.createElement(_reactNative.Text, {
    style: _styles.default.otpLabel
  }, "OTP"), /*#__PURE__*/_react.default.createElement(_reactNative.View, {
    style: _styles.default.otpContainer
  }, /*#__PURE__*/_react.default.createElement(_reactNative.TextInput, {
    value: otpSms,
    onChangeText: setOtpSms,
    style: _styles.default.otpInputContainer,
    keyboardType: "number-pad",
    selectionColor: '#121517',
    maxLength: MAX_LENGTH_OTP
  }), /*#__PURE__*/_react.default.createElement(_reactNative.TouchableOpacity, {
    disabled: otpTimeLeft !== 0,
    onPress: getOtp
  }, /*#__PURE__*/_react.default.createElement(_reactNative.Text, {
    style: [_styles.default.resendText, {
      color: themeColor
    }]
  }, "G\u1EEDi l\u1EA1i (", otpTimeLeft, "s)")))));
};
var _default = DeviceRegistrationView;
exports.default = _default;
//# sourceMappingURL=DeviceRegistrationView.js.map