var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useFetchReactions = void 0;
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _react = require("react");
var _ChatContext = require("../../../contexts/chatContext/ChatContext");
var useFetchReactions = exports.useFetchReactions = function useFetchReactions(_ref) {
  var _ref$limit = _ref.limit,
    limit = _ref$limit === void 0 ? 25 : _ref$limit,
    message = _ref.message,
    reactionType = _ref.reactionType,
    sort = _ref.sort;
  var _useState = (0, _react.useState)([]),
    _useState2 = (0, _slicedToArray2["default"])(_useState, 2),
    reactions = _useState2[0],
    setReactions = _useState2[1];
  var _useState3 = (0, _react.useState)(true),
    _useState4 = (0, _slicedToArray2["default"])(_useState3, 2),
    loading = _useState4[0],
    setLoading = _useState4[1];
  var _useState5 = (0, _react.useState)(undefined),
    _useState6 = (0, _slicedToArray2["default"])(_useState5, 2),
    next = _useState6[0],
    setNext = _useState6[1];
  var messageId = message == null ? void 0 : message.id;
  var _useChatContext = (0, _ChatContext.useChatContext)(),
    client = _useChatContext.client,
    enableOfflineSupport = _useChatContext.enableOfflineSupport;
  var sortString = (0, _react.useMemo)(function () {
    return JSON.stringify(sort);
  }, [sort]);
  var fetchReactions = (0, _react.useCallback)((0, _asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee() {
    var response;
    return _regenerator["default"].wrap(function _callee$(_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          if (messageId) {
            _context.next = 2;
            break;
          }
          return _context.abrupt("return");
        case 2:
          _context.prev = 2;
          _context.next = 5;
          return client.queryReactions(messageId, reactionType ? {
            type: reactionType
          } : {}, sort, {
            limit: limit,
            next: next
          });
        case 5:
          response = _context.sent;
          if (response) {
            setReactions(function (prevReactions) {
              return next ? [].concat((0, _toConsumableArray2["default"])(prevReactions), (0, _toConsumableArray2["default"])(response.reactions)) : response.reactions;
            });
            setNext(response.next);
            setLoading(false);
          }
          _context.next = 12;
          break;
        case 9:
          _context.prev = 9;
          _context.t0 = _context["catch"](2);
          console.log('Error fetching reactions: ', _context.t0);
        case 12:
        case "end":
          return _context.stop();
      }
    }, _callee, null, [[2, 9]]);
  })), [client, messageId, reactionType, sortString, next, limit, enableOfflineSupport]);
  var loadNextPage = (0, _react.useCallback)((0, _asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee2() {
    return _regenerator["default"].wrap(function _callee2$(_context2) {
      while (1) switch (_context2.prev = _context2.next) {
        case 0:
          if (!next) {
            _context2.next = 3;
            break;
          }
          _context2.next = 3;
          return fetchReactions();
        case 3:
        case "end":
          return _context2.stop();
      }
    }, _callee2);
  })), [fetchReactions, next]);
  (0, _react.useEffect)(function () {
    setReactions([]);
    setNext(undefined);
    fetchReactions();
  }, [fetchReactions, messageId, reactionType, sortString]);
  (0, _react.useEffect)(function () {
    var listeners = [];
    listeners.push(client.on('offline_reactions.queried', function (event) {
      var offlineReactions = event.offlineReactions;
      if (offlineReactions) {
        setReactions(offlineReactions);
        setLoading(false);
        setNext(undefined);
      }
    }));
    listeners.push(client.on('reaction.new', function (event) {
      var reaction = event.reaction;
      if (reaction && reaction.type === reactionType) {
        setReactions(function (prevReactions) {
          return [reaction].concat((0, _toConsumableArray2["default"])(prevReactions));
        });
      }
    }));
    listeners.push(client.on('reaction.updated', function (event) {
      var reaction = event.reaction;
      if (reaction) {
        if (reaction.type === reactionType) {
          setReactions(function (prevReactions) {
            return [reaction].concat((0, _toConsumableArray2["default"])(prevReactions));
          });
        } else {
          setReactions(function (prevReactions) {
            return prevReactions.filter(function (r) {
              return r.user_id !== reaction.user_id;
            });
          });
        }
      }
    }));
    listeners.push(client.on('reaction.deleted', function (event) {
      var reaction = event.reaction;
      if (reaction && reaction.type === reactionType) {
        setReactions(function (prevReactions) {
          return prevReactions.filter(function (r) {
            return r.user_id !== reaction.user_id;
          });
        });
      }
    }));
    return function () {
      listeners.forEach(function (listener) {
        listener == null || listener.unsubscribe();
      });
    };
  }, [client, reactionType]);
  return {
    loading: loading,
    loadNextPage: loadNextPage,
    reactions: reactions
  };
};
//# sourceMappingURL=useFetchReactions.js.map