"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _react = _interopRequireWildcard(require("react"));
var _reactNative = require("react-native");
var _reactNativeEventListeners = require("react-native-event-listeners");
var _reactNativeWebview = require("react-native-webview");
var _constants = _interopRequireDefault(require("./constants"));
var _axios = _interopRequireDefault(require("axios"));
var _Services = require("./Services");
var _MainWebView = _interopRequireDefault(require("./MainWebView"));
var _ProgressWebView = _interopRequireDefault(require("./ProgressWebView"));
var _reactNativeActionsSheet = require("react-native-actions-sheet");
require("../src/Sheets");
var _reactRedux = require("react-redux");
var _toolkit = require("@reduxjs/toolkit");
var _core = _interopRequireDefault(require("@redux-saga/core"));
var _slices = _interopRequireDefault(require("./redux/slices"));
var _sagas = _interopRequireDefault(require("./redux/sagas"));
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); }
const {
  MyReactNativeBridge
} = _reactNative.NativeModules;
const LINKING_ERROR = `The package 'react-native-mytatva-rn-sdk' doesn't seem to be linked. Make sure: \n\n` + _reactNative.Platform.select({
  ios: "- You have run 'pod install'\n",
  default: ''
}) + '- You rebuilt the app after installing the package\n' + '- You are not using Expo Go\n';
const escapeChars = {
  lt: '<',
  gt: '>',
  quot: '"',
  apos: "'",
  amp: '&'
};
const unescapeHTML = str =>
// modified from underscore.string and string.js
// eslint-disable-next-line no-useless-escape
str.replace(/\&([^;]+);/g, (entity, entityCode) => {
  let match;
  if (entityCode in escapeChars) {
    return escapeChars[entityCode];
  } else if (match = entityCode.match(/^#x([\da-fA-F]+)$/)) {
    return String.fromCharCode(parseInt(match[1], 16));
  } else if (match = entityCode.match(/^#(\d+)$/)) {
    return String.fromCharCode(match[1]);
  } else {
    return entity;
  }
});
const mytatvaEvent = 'mytatva-event';
const sagaMiddleware = (0, _core.default)();
const store = (0, _toolkit.configureStore)({
  reducer: _slices.default,
  middleware: getDefaultMiddleware => getDefaultMiddleware().concat(sagaMiddleware)
});
sagaMiddleware.run(_sagas.default);
const MyTatvaRnSdkView = ({
  mobileNumber,
  uuid,
  baseUrl,
  errorBaseUrl,
  token,
  environment,
  userMetaInfo,
  clientSource,
  moduleName,
  navigation
}) => {
  const [source, setSource] = (0, _react.useState)('');
  const [loading, setLoading] = (0, _react.useState)(false);
  const [isError, setError] = (0, _react.useState)(false);

  // useEffect(() => {
  //   if ((baseUrl?.trim()?.length || 0) > 0) {
  //     setSource(baseUrl);
  //   }
  // }, [
  //   baseUrl,

  // ]);

  const MyTatvaRnSdkViewManager = (0, _react.useMemo)(() => _reactNative.NativeModules.MyTatvaRnSdkViewManager ? _reactNative.NativeModules.MyTatvaRnSdkViewManager : new Proxy({}, {
    get() {
      throw new Error(LINKING_ERROR);
    }
  }), []);
  (0, _react.useEffect)(() => {
    if (!uuid && !mobileNumber) {
      setTimeout(() => {
        _reactNativeEventListeners.EventRegister.emitEvent('mytatva-event', {
          message: 'unique-identifier',
          errorMessage: 'contact number or patientId is required'
        });
      }, 1000);
      setError(true);
    } else {
      authenticateSDK();
      setError(false);
    }
  }, [uuid, mobileNumber]);
  const webviewRef = (0, _react.useRef)(null);
  const authenticateSDK = () => {
    setLoading(true);
    let baseUrl = environment.toUpperCase() === 'PROD' ? _constants.default.PROD_BASE_URL : _constants.default.STAGE_BASE_URL;
    const finalUrl = baseUrl + '/helper/authenticateClient';
    const data = {
      source: clientSource,
      sourceKey: token
    };
    (0, _axios.default)({
      method: 'post',
      url: finalUrl,
      headers: {
        'api-key': environment.toUpperCase() === 'PROD' ? _constants.default.PROD_API_KEY : _constants.default.STAGE_API_KEY,
        'Content-Type': 'text/plain'
      },
      data: (0, _Services.getEncryptedText)(data, environment)
    }).then(async response => {
      const parsedResponse = await JSON.parse((0, _Services.getDecryptedData)(response === null || response === void 0 ? void 0 : response.data, environment));
      if ((parsedResponse === null || parsedResponse === void 0 ? void 0 : parsedResponse.data) == 0) {
        setError(true);
        _reactNativeEventListeners.EventRegister.emitEvent('mytatva-event', {
          message: 'unauthorized-client',
          errorMessage: 'Unauthorized Access'
        });
      } else {
        getSourceUrl();
      }
    }).catch(error => {
      console.log("error", error);
    }).finally(() => {
      setLoading(false);
    });
  };
  (0, _react.useEffect)(() => {
    const apiManagerEmitter = new _reactNative.NativeEventEmitter(MyTatvaRnSdkViewManager);
    const subscription = apiManagerEmitter.addListener('EventReminder', reminder => {});
    return () => {
      subscription.remove();
    };
  }, [MyTatvaRnSdkViewManager]);
  const getSourceUrl = () => {
    let finalUrl = '';
    const params = {
      uuid,
      mobileNumber,
      clientSource,
      moduleName,
      environment,
      ...userMetaInfo
    };
    let baseUrl = environment.toUpperCase() === 'PROD' ? _constants.default.PROD_BASE_URL : _constants.default.STAGE_BASE_URL;
    if (baseUrl) {
      finalUrl = baseUrl + '?data=' + encodeURIComponent(JSON.stringify(params));
      setSource(finalUrl);
    } else {
      console.log("No baseUrl");
    }
  };
  const handleMessage = async event => {
    var _webviewRef$current;
    const data = JSON.parse(unescapeHTML(event.nativeEvent.data));
    const {
      method,
      url
    } = data;
    switch (method) {
      case 'UPDATE_PLATFORM':
        (_webviewRef$current = webviewRef.current) === null || _webviewRef$current === void 0 || _webviewRef$current.injectJavaScript('window.setSdkPlatform("IOS")');
        break;
      case 'OPEN_PDF':
        _reactNative.Linking.openURL(url);
        break;
      case 'CLOSE_VIEW':
        break;
      default:
        break;
    }
  };
  const [canGoBack, setCanGoBack] = (0, _react.useState)(false);
  const handleBack = (0, _react.useCallback)(() => {
    if (canGoBack && webviewRef.current) {
      var _webviewRef$current2;
      (_webviewRef$current2 = webviewRef.current) === null || _webviewRef$current2 === void 0 || _webviewRef$current2.goBack();
      return true;
    }
    return false;
  }, [canGoBack]);
  (0, _react.useEffect)(() => {
    _reactNative.BackHandler.addEventListener('hardwareBackPress', handleBack);
    return () => {
      _reactNative.BackHandler.removeEventListener('hardwareBackPress', handleBack);
      // gpsListener.remove();
    };
  }, [handleBack]);
  const openNativeScreen = () => {
    MyReactNativeBridge.openNativeFlow();
  };
  const {
    height,
    width
  } = _reactNative.Dimensions.get('screen');
  return (
    /*#__PURE__*/
    // eslint-disable-next-line react-native/no-inline-styles
    _react.default.createElement(_reactNative.SafeAreaView, {
      style: {
        flex: 1,
        backgroundColor: 'white'
      }
    }, /*#__PURE__*/_react.default.createElement(_reactRedux.Provider, {
      store: store
    }, /*#__PURE__*/_react.default.createElement(_reactNativeActionsSheet.SheetProvider, null, /*#__PURE__*/_react.default.createElement(_reactNative.Button, {
      title: "Open CGM",
      color: "#f194ff",
      onPress: openNativeScreen
    }), moduleName === 'progress' ? /*#__PURE__*/_react.default.createElement(_ProgressWebView.default, {
      token: token,
      environment: environment,
      source: source,
      loading: loading,
      isError: isError,
      webviewRef: webviewRef
      // runBeforeFirst={runBeforeFirst}
      ,
      setCanGoBack: setCanGoBack,
      mobileNumber: mobileNumber,
      moduleName: moduleName,
      platform: 'IOS',
      uuid: uuid,
      clientSource: clientSource
    }) : /*#__PURE__*/_react.default.createElement(_MainWebView.default, {
      token: token,
      environment: environment,
      source: source,
      loading: loading,
      platform: 'IOS',
      isError: isError,
      webviewRef: webviewRef,
      handleMessage: handleMessage
      // runBeforeFirst={runBeforeFirst}
      ,
      setCanGoBack: setCanGoBack,
      clientSource: clientSource,
      moduleName: moduleName
    }))))
  );
};
const styles = _reactNative.StyleSheet.create({
  webViewContainer: {
    flex: 1,
    backgroundColor: 'white'
  },
  webView: {
    flex: 1
  }
});
MyTatvaRnSdkView.defaultProps = {
  mobileNumber: '',
  uuid: '',
  token: '',
  baseUrl: '',
  errorBaseUrl: '',
  environment: '',
  metaInfo: {},
  clientSource: '',
  moduleName: ''
};
var _default = exports.default = MyTatvaRnSdkView;
const LoadingIndicator = () => {
  return /*#__PURE__*/_react.default.createElement(_reactNative.ActivityIndicator, {
    color: "#000",
    size: "small"
    // eslint-disable-next-line react-native/no-inline-styles
    ,
    style: {
      flex: 1,
      zIndex: 100,
      position: 'absolute',
      backgroundColor: '#fff',
      opacity: 0.4,
      width: '100%',
      height: '100%',
      justifyContent: 'center',
      alignItems: 'center'
    }
  });
};
//# sourceMappingURL=MyTatvaRnSdkView.ios.js.map