var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _typeof = require("@babel/runtime/helpers/typeof");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Chat = 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 = _interopRequireWildcard(require("react"));
var _reactNative = require("react-native");
var _useAppSettings = require("./hooks/useAppSettings");
var _useCreateChatContext = require("./hooks/useCreateChatContext");
var _useIsOnline2 = require("./hooks/useIsOnline");
var _useMutedUsers = require("./hooks/useMutedUsers");
var _ChannelsStateContext = require("../../contexts/channelsStateContext/ChannelsStateContext");
var _ChatContext = require("../../contexts/chatContext/ChatContext");
var _DebugContext = require("../../contexts/debugContext/DebugContext");
var _OverlayContext = require("../../contexts/overlayContext/OverlayContext");
var _ThemeContext = require("../../contexts/themeContext/ThemeContext");
var _TranslationContext = require("../../contexts/translationContext/TranslationContext");
var _hooks = require("../../hooks");
var _useStreami18n = require("../../hooks/useStreami18n");
var _init = _interopRequireDefault(require("../../init"));
var _native = require("../../native");
var _OfflineDB = require("../../store/OfflineDB");
var _version = require("../../version.json");
var _jsxRuntime = require("react/jsx-runtime");
var _this = this,
  _jsxFileName = "/home/runner/work/stream-chat-react-native/stream-chat-react-native/package/src/components/Chat/Chat.tsx";
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { "default": e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n["default"] = e, t && t.set(e, n), n; }
(0, _init["default"])();
var selector = function selector(nextValue) {
  return {
    initialized: nextValue.initialized,
    userId: nextValue.userId
  };
};
var ChatWithContext = function ChatWithContext(props) {
  var _useStateStore, _client$offlineDb, _client$user;
  var children = props.children,
    client = props.client,
    _props$closeConnectio = props.closeConnectionOnBackground,
    closeConnectionOnBackground = _props$closeConnectio === void 0 ? true : _props$closeConnectio,
    _props$enableOfflineS = props.enableOfflineSupport,
    enableOfflineSupport = _props$enableOfflineS === void 0 ? false : _props$enableOfflineS,
    i18nInstance = props.i18nInstance,
    _props$ImageComponent = props.ImageComponent,
    ImageComponent = _props$ImageComponent === void 0 ? _reactNative.Image : _props$ImageComponent,
    isMessageAIGenerated = props.isMessageAIGenerated,
    _props$LoadingIndicat = props.LoadingIndicator,
    LoadingIndicator = _props$LoadingIndicat === void 0 ? null : _props$LoadingIndicat,
    style = props.style;
  var _useState = (0, _react.useState)(),
    _useState2 = (0, _slicedToArray2["default"])(_useState, 2),
    channel = _useState2[0],
    setChannel = _useState2[1];
  var translators = (0, _useStreami18n.useStreami18n)(i18nInstance);
  var _useIsOnline = (0, _useIsOnline2.useIsOnline)(client, closeConnectionOnBackground),
    connectionRecovering = _useIsOnline.connectionRecovering,
    isOnline = _useIsOnline.isOnline;
  var _ref = (_useStateStore = (0, _hooks.useStateStore)((_client$offlineDb = client.offlineDb) == null ? void 0 : _client$offlineDb.state, selector)) != null ? _useStateStore : {},
    offlineDbInitialized = _ref.initialized,
    offlineDbUserId = _ref.userId;
  var mutedUsers = (0, _useMutedUsers.useMutedUsers)(client);
  var debugRef = (0, _DebugContext.useDebugContext)();
  var isDebugModeEnabled = __DEV__ && debugRef && debugRef.current;
  var userID = client.userID;
  (0, _react.useEffect)(function () {
    if (client) {
      var sdkName = _native.NativeHandlers.SDK ? _native.NativeHandlers.SDK.replace('stream-chat-', '') : 'react-native';
      client.sdkIdentifier = {
        name: sdkName,
        version: _version.version
      };
      client.deviceIdentifier = {
        os: "".concat(_reactNative.Platform.OS, " ").concat(_reactNative.Platform.Version)
      };
      client.recoverStateOnReconnect = false;
      client.persistUserOnConnectionFailure = enableOfflineSupport;
    }
    if (isDebugModeEnabled) {
      if (debugRef.current.setEventType) {
        debugRef.current.setEventType('send');
      }
      if (debugRef.current.setSendEventParams) {
        debugRef.current.setSendEventParams({
          action: 'Client',
          data: client.user
        });
      }
    }
  }, [client, enableOfflineSupport]);
  var setActiveChannel = function setActiveChannel(newChannel) {
    return setChannel(newChannel);
  };
  (0, _react.useEffect)(function () {
    if (!(userID && enableOfflineSupport)) {
      return;
    }
    var initializeDatabase = function () {
      var _ref2 = (0, _asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee() {
        return _regenerator["default"].wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              if (!client.offlineDb) {
                client.setOfflineDBApi(new _OfflineDB.OfflineDB({
                  client: client
                }));
              }
              if (!client.offlineDb) {
                _context.next = 4;
                break;
              }
              _context.next = 4;
              return client.offlineDb.init(userID);
            case 4:
            case "end":
              return _context.stop();
          }
        }, _callee);
      }));
      return function initializeDatabase() {
        return _ref2.apply(this, arguments);
      };
    }();
    initializeDatabase();
  }, [userID, enableOfflineSupport, client]);
  (0, _react.useEffect)(function () {
    if (!client) {
      return;
    }
    client.threads.registerSubscriptions();
    client.polls.registerSubscriptions();
    return function () {
      client.threads.unregisterSubscriptions();
      client.polls.unregisterSubscriptions();
    };
  }, [client]);
  var initialisedDatabase = !!offlineDbInitialized && userID === offlineDbUserId;
  var appSettings = (0, _useAppSettings.useAppSettings)(client, isOnline, enableOfflineSupport, initialisedDatabase);
  var chatContext = (0, _useCreateChatContext.useCreateChatContext)({
    appSettings: appSettings,
    channel: channel,
    client: client,
    connectionRecovering: connectionRecovering,
    enableOfflineSupport: enableOfflineSupport,
    ImageComponent: ImageComponent,
    isMessageAIGenerated: isMessageAIGenerated,
    isOnline: isOnline,
    mutedUsers: mutedUsers,
    setActiveChannel: setActiveChannel
  });
  if (userID && enableOfflineSupport && !initialisedDatabase) {
    return LoadingIndicator ? (0, _jsxRuntime.jsx)(LoadingIndicator, {}) : null;
  }
  return (0, _jsxRuntime.jsx)(_ChatContext.ChatProvider, {
    value: chatContext,
    children: (0, _jsxRuntime.jsx)(_TranslationContext.TranslationProvider, {
      value: Object.assign({}, translators, {
        userLanguage: ((_client$user = client.user) == null ? void 0 : _client$user.language) || _TranslationContext.DEFAULT_USER_LANGUAGE
      }),
      children: (0, _jsxRuntime.jsx)(_ThemeContext.ThemeProvider, {
        style: style,
        children: (0, _jsxRuntime.jsx)(_ChannelsStateContext.ChannelsStateProvider, {
          children: children
        })
      })
    })
  });
};
var Chat = exports.Chat = function Chat(props) {
  var _useOverlayContext = (0, _OverlayContext.useOverlayContext)(),
    style = _useOverlayContext.style;
  return (0, _jsxRuntime.jsx)(ChatWithContext, Object.assign({
    style: style
  }, props));
};
//# sourceMappingURL=Chat.js.map