var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.usePaginatedChannels = void 0;
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _react = require("react");
var _ActiveChannelsRefContext = require("../../../contexts/activeChannelsRefContext/ActiveChannelsRefContext");
var _ChatContext = require("../../../contexts/chatContext/ChatContext");
var _hooks = require("../../../hooks");
var _useIsMountedRef = require("../../../hooks/useIsMountedRef");
var _utils = require("../utils");
var DEFAULT_OPTIONS = {
  message_limit: 10
};
var RETRY_INTERVAL_IN_MS = 5000;
var selector = function selector(nextValue) {
  return {
    channelListInitialized: nextValue.initialized,
    channels: nextValue.channels,
    error: nextValue.error,
    pagination: nextValue.pagination
  };
};
var usePaginatedChannels = exports.usePaginatedChannels = function usePaginatedChannels(_ref) {
  var _useStateStore;
  var channelManager = _ref.channelManager,
    enableOfflineSupport = _ref.enableOfflineSupport,
    _ref$filters = _ref.filters,
    filters = _ref$filters === void 0 ? {} : _ref$filters,
    _ref$options = _ref.options,
    options = _ref$options === void 0 ? DEFAULT_OPTIONS : _ref$options,
    _ref$sort = _ref.sort,
    sort = _ref$sort === void 0 ? {} : _ref$sort;
  var _useState = (0, _react.useState)(false),
    _useState2 = (0, _slicedToArray2["default"])(_useState, 2),
    staticChannelsActive = _useState2[0],
    setStaticChannelsActive = _useState2[1];
  var _useState3 = (0, _react.useState)('queryLocalDB'),
    _useState4 = (0, _slicedToArray2["default"])(_useState3, 2),
    activeQueryType = _useState4[0],
    setActiveQueryType = _useState4[1];
  var activeChannels = (0, _ActiveChannelsRefContext.useActiveChannelsRefContext)();
  var isMountedRef = (0, _useIsMountedRef.useIsMountedRef)();
  var _useChatContext = (0, _ChatContext.useChatContext)(),
    client = _useChatContext.client;
  var _ref2 = (_useStateStore = (0, _hooks.useStateStore)(channelManager == null ? void 0 : channelManager.state, selector)) != null ? _useStateStore : {},
    channelListInitialized = _ref2.channelListInitialized,
    channels = _ref2.channels,
    pagination = _ref2.pagination,
    error = _ref2.error;
  var hasNextPage = pagination == null ? void 0 : pagination.hasNext;
  var filtersRef = (0, _react.useRef)(null);
  var sortRef = (0, _react.useRef)(null);
  var activeRequestId = (0, _react.useRef)(0);
  var isQueryingRef = (0, _react.useRef)(false);
  var lastRefresh = (0, _react.useRef)(Date.now());
  var queryChannels = function () {
    var _ref3 = (0, _asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee() {
      var _options$limit;
      var queryType,
        hasUpdatedData,
        isQueryStale,
        currentRequestId,
        newOptions,
        _args = arguments;
      return _regenerator["default"].wrap(function _callee$(_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            queryType = _args.length > 0 && _args[0] !== undefined ? _args[0] : 'loadChannels';
            if (!(!client || !isMountedRef.current)) {
              _context.next = 3;
              break;
            }
            return _context.abrupt("return");
          case 3:
            hasUpdatedData = queryType === 'loadChannels' || queryType === 'refresh' || [JSON.stringify(filtersRef.current) !== JSON.stringify(filters), JSON.stringify(sortRef.current) !== JSON.stringify(sort)].some(Boolean);
            isQueryStale = function isQueryStale() {
              return !isMountedRef || activeRequestId.current !== currentRequestId;
            };
            if (hasUpdatedData) {
              _context.next = 8;
              break;
            }
            if (!(activeQueryType === null)) {
              _context.next = 8;
              break;
            }
            return _context.abrupt("return");
          case 8:
            filtersRef.current = filters;
            sortRef.current = sort;
            isQueryingRef.current = true;
            activeRequestId.current++;
            currentRequestId = activeRequestId.current;
            setActiveQueryType(queryType);
            newOptions = Object.assign({
              limit: (_options$limit = options == null ? void 0 : options.limit) != null ? _options$limit : _utils.MAX_QUERY_CHANNELS_LIMIT,
              offset: 0
            }, options);
            _context.prev = 15;
            if (!(isQueryStale() || !isMountedRef.current)) {
              _context.next = 18;
              break;
            }
            return _context.abrupt("return");
          case 18:
            if (!(queryType === 'loadChannels')) {
              _context.next = 23;
              break;
            }
            _context.next = 21;
            return channelManager.loadNext();
          case 21:
            _context.next = 25;
            break;
          case 23:
            _context.next = 25;
            return channelManager.queryChannels(filters, sort, newOptions, {
              skipInitialization: enableOfflineSupport ? undefined : activeChannels.current
            });
          case 25:
            setStaticChannelsActive(false);
            isQueryingRef.current = false;
            _context.next = 35;
            break;
          case 29:
            _context.prev = 29;
            _context.t0 = _context["catch"](15);
            isQueryingRef.current = false;
            if (!isQueryStale()) {
              _context.next = 34;
              break;
            }
            return _context.abrupt("return");
          case 34:
            console.warn(_context.t0);
          case 35:
            setActiveQueryType(null);
          case 36:
          case "end":
            return _context.stop();
        }
      }, _callee, null, [[15, 29]]);
    }));
    return function queryChannels() {
      return _ref3.apply(this, arguments);
    };
  }();
  var refreshList = function () {
    var _ref4 = (0, _asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee2() {
      var now;
      return _regenerator["default"].wrap(function _callee2$(_context2) {
        while (1) switch (_context2.prev = _context2.next) {
          case 0:
            now = Date.now();
            if (!(now - lastRefresh.current < RETRY_INTERVAL_IN_MS && error === undefined)) {
              _context2.next = 3;
              break;
            }
            return _context2.abrupt("return");
          case 3:
            lastRefresh.current = Date.now();
            _context2.next = 6;
            return queryChannels('refresh');
          case 6:
          case "end":
            return _context2.stop();
        }
      }, _callee2);
    }));
    return function refreshList() {
      return _ref4.apply(this, arguments);
    };
  }();
  var reloadList = function () {
    var _ref5 = (0, _asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee3() {
      return _regenerator["default"].wrap(function _callee3$(_context3) {
        while (1) switch (_context3.prev = _context3.next) {
          case 0:
            _context3.next = 2;
            return queryChannels('reload');
          case 2:
          case "end":
            return _context3.stop();
        }
      }, _callee3);
    }));
    return function reloadList() {
      return _ref5.apply(this, arguments);
    };
  }();
  var filterStr = (0, _react.useMemo)(function () {
    return JSON.stringify(filters);
  }, [filters]);
  var sortStr = (0, _react.useMemo)(function () {
    return JSON.stringify(sort);
  }, [sort]);
  (0, _react.useEffect)(function () {
    var listener = client.on('connection.changed', function () {
      var _ref6 = (0, _asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee4(event) {
        return _regenerator["default"].wrap(function _callee4$(_context4) {
          while (1) switch (_context4.prev = _context4.next) {
            case 0:
              if (!event.online) {
                _context4.next = 3;
                break;
              }
              _context4.next = 3;
              return refreshList();
            case 3:
            case "end":
              return _context4.stop();
          }
        }, _callee4);
      }));
      return function (_x) {
        return _ref6.apply(this, arguments);
      };
    }());
    reloadList();
    return function () {
      return listener == null || listener.unsubscribe == null ? void 0 : listener.unsubscribe();
    };
  }, [filterStr, sortStr, channelManager]);
  return {
    channelListInitialized: channelListInitialized,
    channels: channels,
    error: error,
    hasNextPage: hasNextPage,
    loadingChannels: activeQueryType === 'queryLocalDB' ? true : (pagination == null ? void 0 : pagination.isLoading) || !channelListInitialized && channels.length === 0 && !error,
    loadingNextPage: pagination == null ? void 0 : pagination.isLoadingNext,
    loadNextPage: channelManager.loadNext,
    refreshing: activeQueryType === 'refresh',
    refreshList: refreshList,
    reloadList: reloadList,
    staticChannelsActive: staticChannelsActive
  };
};
//# sourceMappingURL=usePaginatedChannels.js.map