"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.httpClient = exports.default = void 0;
var _react = _interopRequireWildcard(require("react"));
var _reactNativeEventListeners = require("react-native-event-listeners");
var _native = require("@react-navigation/native");
var _reactNative = require("react-native");
require("./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"));
var _axios = _interopRequireDefault(require("axios"));
var _constants = _interopRequireDefault(require("./constants"));
var _Services = require("./Services");
var _MainWebView = _interopRequireDefault(require("./MainWebView"));
var _ProgressWebView = _interopRequireDefault(require("./ProgressWebView"));
var _reactNativeActionsSheet = require("react-native-actions-sheet");
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); }
// import { createStackNavigator } from '@react-navigation/stack';

// import {enableScreens} from 'react-native-screens';

// enableScreens();

// const Stack = createStackNavigator();

const httpClient = exports.httpClient = _axios.default.create({
  timeout: 60000,
  headers: {
    'api-key': 'lChjFRJce3bxmoS3TSQk5w==',
    'Content-Type': 'text/plain'
  }
});
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 [appState, setAppState] = (0, _react.useState)(_reactNative.AppState.currentState);
  const [loading, setLoading] = (0, _react.useState)(false);
  const [isError, setError] = (0, _react.useState)(false);

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

  (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]);
  (0, _react.useEffect)(() => {
    const subscription = _reactNative.AppState.addEventListener('change', handleAppStateChange);
    console.log(`AppState.addEventListener added, current state: ${appState}`);
    return () => {
      subscription.remove();
    };
  }, [appState]); // Include appState in the dependency array to ensure it's up to date.

  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);
    });
  };
  const handleAppStateChange = nextAppState => {
    // console.log(
    //   "nextAppState: " + nextAppState + ", previousState: " + appState
    // );

    // Instead of relying on the old appState, use the nextAppState directly
    if (appState.match(/inactive|background/) && nextAppState === 'active') {
      if (isLoggingEnabled) {
        console.log('App has come to the foreground!');
      }
      // getHealthConnectStatus();
    }

    // setAppState(nextAppState); // Update the state with the new app state
  };
  const webviewRef = (0, _react.useRef)(null);
  const runBeforeFirst = `
        window.isNativeApp = true;
        window.platform = "ANDROID";
        window.setSdkPlatform('ANDROID');
        true; // note: this is required, or you'll sometimes get silent failures
    `;

  // console.log("runBeforeFirst====", runBeforeFirst)
  const handleMessage = event => {
    var _webviewRef$current;
    console.log("event====", event);
    if (event.nativeEvent.data != null) {
      try {
        const parsedObject = JSON.parse(event.nativeEvent.data);
        if (parsedObject.method != null) {
          switch (parsedObject.method) {
            case 'UPDATE_PLATFORM':
              (_webviewRef$current = webviewRef.current) === null || _webviewRef$current === void 0 || _webviewRef$current.injectJavaScript('window.setSdkPlatform("ANDROID")');
              break;
            case 'OPEN_PDF':
              {
                let pdfUrl = parsedObject.url;
                // console.log("pdfUrl "+pdfUrl);

                _reactNative.Linking.openURL(pdfUrl);
              }
              break;
            case 'CLOSE_VIEW':
              break;
            case 'OPEN_URL_HANDLER':
              navigation.navigate('UrlHandler', {
                url: parsedObject.url
              });
              break;
            case 'START_CGM_TRACKY':
              break;
            default:
              break;
          }
        }
      } catch (exception) {
        console.log('Exception occurred:' + exception.message);
      }
    }
  };
  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 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 startCgm = async () => {
    try {
      const result = await CgmTrackyLib.startCgmTracky();
      console.log(result);
    } catch (error) {
      console.error(error);
    }
  };
  const observeCgmData = async () => {
    try {
      CgmTrackyLib.observeAllGlucoseData();
      CgmTrackyLib.observeDeviceStatus();
    } catch (error) {
      console.error(error);
    }
  };
  const observeDeviceStaus = async () => {
    try {
      const result = await CgmTrackyLib.observeDeviceStatus();
      console.log(result);
    } catch (error) {
      console.error(error);
    }
  };
  return /*#__PURE__*/_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: "Press me",
    color: "#f194ff",
    onPress: startCgm
  }), /*#__PURE__*/_react.default.createElement(_reactNative.Button, {
    title: "Observe CGM Data",
    color: "#008000",
    onPress: observeCgmData
  }), /*#__PURE__*/_react.default.createElement(_reactNative.Button, {
    title: "Observe Device Status",
    color: "#427ef5",
    onPress: observeDeviceStaus
  }), 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,
    platform: 'ANDROID',
    moduleName: moduleName,
    uuid: uuid,
    clientSource: clientSource
  }) : /*#__PURE__*/_react.default.createElement(_MainWebView.default, {
    token: token,
    environment: environment,
    source: source,
    loading: loading,
    platform: 'ANDROID',
    isError: isError,
    webviewRef: webviewRef,
    handleMessage: handleMessage,
    runBeforeFirst: runBeforeFirst,
    setCanGoBack: setCanGoBack,
    clientSource: clientSource,
    moduleName: moduleName
  }))));
};
var _default = exports.default = MyTatvaRnSdkView;
MyTatvaRnSdkView.defaultProps = {
  mobileNumber: '',
  uuid: '',
  token: '',
  baseUrl: '',
  errorBaseUrl: '',
  environment: '',
  metaInfo: {},
  clientSource: '',
  moduleName: '',
  navigation: {}
};
//# sourceMappingURL=MyTatvaRnSdkView.android.js.map