"use strict";

exports.__esModule = true;
exports.InfinityLoader = InfinityLoader;

var _react = _interopRequireWildcard(require("react"));

var _useElementOnScreen = require("../../hooks/useElementOnScreen");

var _jsxRuntime = require("react/jsx-runtime");

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 InfinityLoader(props) {
  var initialObserverOptions = {
    root: null,
    rootMargin: "0px",
    threshold: 1.0
  };
  const {
    totalPages = -1,
    observerOptions,
    children,
    loadingComponent,
    showLoading = true,
    getData = () => Promise.resolve({}),
    onLoadMore = null,
    onSuccess = null,
    onError = null,
    wrapperStyles = {},
    loadingStyles = {},
    listStyles = {},
    renderItem = null,
    renderParent = props => /*#__PURE__*/(0, _jsxRuntime.jsx)("div", { ...props
    }),
    dependencies = []
  } = props;
  const {
    containerRef,
    isVisible
  } = (0, _useElementOnScreen.useElementOnScreen)(observerOptions || initialObserverOptions);
  const [data, setData] = (0, _react.useState)([]);
  const [loading, setLoading] = (0, _react.useState)(false);
  const [page, setPage] = (0, _react.useState)(0); // Data fetch effect

  (0, _react.useEffect)(() => {
    loadData(page, "add");
  }, [isVisible]); // Reload dependencies Effect

  (0, _react.useEffect)(() => {
    setData([]);
    setPage(0);
    loadData(0, "set");
  }, [...dependencies]);

  function loadData(newPage, action = "add") {
    // if the new page to load is bigger than the total pages, do nothing
    // ignore when total pages is infinite
    if (newPage > totalPages && totalPages !== -1) return;
    setLoading(true);
    onLoadMore && onLoadMore(newPage);
    getData(newPage).then(res => {
      switch (action) {
        case "add":
          setData([...data, ...res]);
          break;

        default:
        case "set":
          setData(res);
          break;
      }

      setLoading(false);
      setPage(newPage + 1);
      onSuccess && onSuccess(res);
    }).catch(error => {
      setLoading(false);
      onError && onError(error);
    });
  }

  const baseParentStyles = {
    display: "flex",
    flexDirection: "column"
  };
  const parentChild = /*#__PURE__*/(0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
    children: [children, data.map((value, index) => {
      return renderItem ? renderItem(value, index) : /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
        children: JSON.stringify(value)
      });
    })]
  });
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
    style: wrapperStyles,
    children: [renderParent({
      children: parentChild,
      style: { ...baseParentStyles,
        ...listStyles
      }
    }), !loading && /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
      ref: containerRef,
      style: {
        width: "100%",
        ...loadingStyles
      }
    }), loading && showLoading && loadingComponent]
  });
}