"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.AuthContextProvider = exports.AuthContext = void 0;
var _react = require("react");
var _tsSdkReactNative = require("@amityco/ts-sdk-react-native");
var _reactNative = require("react-native");
var _constants = require("../../core/constants");
var _navigation = require("../routes/navigation");
const AuthContext = exports.AuthContext = /*#__PURE__*/(0, _react.createContext)({
  client: null,
  isConnecting: false,
  error: '',
  login: () => {},
  logout: () => {},
  isConnected: false,
  sessionState: '',
  apiRegion: 'sg',
  authToken: '',
  fcmToken: undefined,
  isGlobalBan: false
});
const AuthContextProvider = ({
  userId,
  displayName,
  apiKey,
  apiRegion,
  apiEndpoint,
  children,
  authToken,
  fcmToken
}) => {
  const [error, setError] = (0, _react.useState)('');
  const [isConnecting, setLoading] = (0, _react.useState)(false);
  const [isConnected, setIsConnected] = (0, _react.useState)(false);
  const [sessionState, setSessionState] = (0, _react.useState)('');
  const client = _tsSdkReactNative.Client.createClient(apiKey, apiRegion, {
    apiEndpoint: {
      http: apiEndpoint
    }
  });
  const [isGlobalBan, setIsGlobalBan] = (0, _react.useState)(false);
  const sessionHandler = {
    sessionWillRenewAccessToken(renewal) {
      renewal.renew();
    }
  };
  (0, _react.useEffect)(() => {
    return _tsSdkReactNative.Client.onSessionStateChange((state, reason) => {
      setSessionState(state);
      setIsGlobalBan(reason === 'globalBan');
    });
  }, []);
  (0, _react.useEffect)(() => {
    if (sessionState === 'established') {
      setIsConnected(true);
      (0, _navigation.onSdkReady)();
    }
  }, [sessionState]);
  const handleConnect = (0, _react.useCallback)(async () => {
    let loginParam;
    loginParam = {
      userId: userId,
      displayName: displayName
    };
    if ((authToken === null || authToken === void 0 ? void 0 : authToken.length) > 0) {
      loginParam = {
        ...loginParam,
        authToken: authToken
      };
    }
    try {
      const response = await _tsSdkReactNative.Client.login(loginParam, sessionHandler);
      if (!response) return;
    } catch (err) {
      var _err$message;
      if (err !== null && err !== void 0 && (_err$message = err.message) !== null && _err$message !== void 0 && _err$message.includes(_constants.ERROR_CODE.GLOBAL_BAN)) {
        setIsGlobalBan(true);
      }
    }
    if (fcmToken) {
      try {
        await _tsSdkReactNative.Client.registerPushNotification(fcmToken);
      } catch (err) {
        console.log(err);
      }
    }
  }, []);
  const login = async () => {
    setError('');
    setLoading(true);
    try {
      await handleConnect();
    } catch (e) {
      const errorText = (e === null || e === void 0 ? void 0 : e.message) ?? 'Error while handling request!';
      setError(errorText);
      throw e;
    } finally {
      setLoading(false);
    }
  };
  (0, _react.useEffect)(() => {
    login();
  }, [userId]);
  const logout = async () => {
    try {
      _tsSdkReactNative.Client.stopUnreadSync();
      await _tsSdkReactNative.Client.logout();
    } catch (e) {
      const errorText = (e === null || e === void 0 ? void 0 : e.message) ?? 'Error while handling request!';
      _reactNative.Alert.alert(errorText);
    }
  };
  return /*#__PURE__*/React.createElement(AuthContext.Provider, {
    value: {
      error,
      isConnecting,
      login,
      client,
      logout,
      isConnected,
      sessionState,
      apiRegion: apiRegion.toLowerCase(),
      isGlobalBan
    }
  }, children);
};
exports.AuthContextProvider = AuthContextProvider;
var _default = exports.default = AuthContextProvider;
//# sourceMappingURL=AuthProvider.js.map