"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _react = _interopRequireWildcard(require("react"));
var _reactNative = require("react-native");
var _reactNativeWebview = require("react-native-webview");
var _jsxRuntime = require("react/jsx-runtime");
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 MAX_ATTEMPTS = 6;
const LOAD_BUDGET_MS = 8000;
const ATTEMPT_TIMEOUT_MS = 3000;
const RENDER_POLLER = `
(function () {
  if (window.__ethoraGviewProbe) { return; }
  window.__ethoraGviewProbe = true;
  var tries = 0;
  function rendered() {
    try {
      var imgs = document.querySelectorAll('img');
      for (var i = 0; i < imgs.length; i++) {
        // naturalHeight is readable even for cross-origin images; gview's
        // page images are tall, the preparing page has none.
        if (imgs[i].naturalHeight > 80) { return true; }
      }
      // Some gview render paths paint pages into <canvas> instead.
      var canvases = document.querySelectorAll('canvas');
      for (var j = 0; j < canvases.length; j++) {
        if (canvases[j].height > 80) { return true; }
      }
      var txt = ((document.body && document.body.innerText) || '').trim();
      return txt.length > 80;
    } catch (e) {
      return false;
    }
  }
  function tick() {
    tries++;
    if (rendered()) {
      try {
        window.ReactNativeWebView.postMessage(JSON.stringify({ rendered: true }));
      } catch (e) {}
      return;
    }
    if (tries < 40) { setTimeout(tick, 500); }
  }
  tick();
})();
true;
`;
const GViewWebView = ({
  url,
  onError
}) => {
  const [attempt, setAttempt] = (0, _react.useState)(0);
  const [ready, setReady] = (0, _react.useState)(false);
  const readyRef = (0, _react.useRef)(false);
  const attemptRef = (0, _react.useRef)(0);
  const watchdog = (0, _react.useRef)(null);
  const viewerUrl = `https://docs.google.com/gview?embedded=true&url=${encodeURIComponent(url)}`;
  const clearWatchdog = () => {
    if (watchdog.current) {
      clearTimeout(watchdog.current);
      watchdog.current = null;
    }
  };
  const giveUpAttempt = (0, _react.useCallback)(() => {
    if (readyRef.current) {
      return;
    }
    if (attemptRef.current < MAX_ATTEMPTS - 1) {
      attemptRef.current += 1;
      setAttempt(attemptRef.current);
    } else {
      readyRef.current = true;
      setReady(true);
    }
  }, []);
  (0, _react.useEffect)(() => {
    if (readyRef.current) {
      return;
    }
    clearWatchdog();
    watchdog.current = setTimeout(giveUpAttempt, LOAD_BUDGET_MS);
    return clearWatchdog;
  }, [attempt, giveUpAttempt]);
  const handleLoadEnd = (0, _react.useCallback)(() => {
    if (readyRef.current) {
      return;
    }
    clearWatchdog();
    watchdog.current = setTimeout(giveUpAttempt, ATTEMPT_TIMEOUT_MS);
  }, [giveUpAttempt]);
  const handleMessage = (0, _react.useCallback)(e => {
    let isRendered = false;
    try {
      isRendered = !!JSON.parse(e.nativeEvent.data)?.rendered;
    } catch {
      isRendered = false;
    }
    if (isRendered && !readyRef.current) {
      clearWatchdog();
      readyRef.current = true;
      setReady(true);
    }
  }, []);
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)(_reactNative.View, {
    style: styles.container,
    children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNativeWebview.WebView, {
      source: {
        uri: viewerUrl
      },
      style: styles.webview,
      originWhitelist: ['*'],
      injectedJavaScript: RENDER_POLLER,
      onLoadEnd: handleLoadEnd,
      onMessage: handleMessage,
      onError: onError,
      onHttpError: onError
    }, attempt), !ready && /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.View, {
      style: styles.loadingOverlay,
      pointerEvents: "none",
      children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.ActivityIndicator, {
        size: "large"
      })
    })]
  });
};
var _default = exports.default = GViewWebView;
const styles = _reactNative.StyleSheet.create({
  container: {
    flex: 1,
    width: '100%',
    backgroundColor: '#fff'
  },
  webview: {
    flex: 1,
    backgroundColor: '#fff'
  },
  loadingOverlay: {
    ..._reactNative.StyleSheet.absoluteFillObject,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#ffffff'
  }
});
//# sourceMappingURL=GViewWebView.js.map