import { createContext, useCallback, useEffect, useState } from 'react';
import { Client } from '@amityco/ts-sdk-react-native';
import { Alert } from 'react-native';
import { ERROR_CODE } from '../../core/constants';
import { onSdkReady } from '../routes/navigation';
export const AuthContext = /*#__PURE__*/createContext({
  client: null,
  isConnecting: false,
  error: '',
  login: () => {},
  logout: () => {},
  isConnected: false,
  sessionState: '',
  apiRegion: 'sg',
  authToken: '',
  fcmToken: undefined,
  isGlobalBan: false
});
export const AuthContextProvider = ({
  userId,
  displayName,
  apiKey,
  apiRegion,
  apiEndpoint,
  children,
  authToken,
  fcmToken
}) => {
  const [error, setError] = useState('');
  const [isConnecting, setLoading] = useState(false);
  const [isConnected, setIsConnected] = useState(false);
  const [sessionState, setSessionState] = useState('');
  const client = Client.createClient(apiKey, apiRegion, {
    apiEndpoint: {
      http: apiEndpoint
    }
  });
  const [isGlobalBan, setIsGlobalBan] = useState(false);
  const sessionHandler = {
    sessionWillRenewAccessToken(renewal) {
      renewal.renew();
    }
  };
  useEffect(() => {
    return Client.onSessionStateChange((state, reason) => {
      setSessionState(state);
      setIsGlobalBan(reason === 'globalBan');
    });
  }, []);
  useEffect(() => {
    if (sessionState === 'established') {
      setIsConnected(true);
      onSdkReady();
    }
  }, [sessionState]);
  const handleConnect = 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 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(ERROR_CODE.GLOBAL_BAN)) {
        setIsGlobalBan(true);
      }
    }
    if (fcmToken) {
      try {
        await 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);
    }
  };
  useEffect(() => {
    login();
  }, [userId]);
  const logout = async () => {
    try {
      Client.stopUnreadSync();
      await Client.logout();
    } catch (e) {
      const errorText = (e === null || e === void 0 ? void 0 : e.message) ?? 'Error while handling request!';
      Alert.alert(errorText);
    }
  };
  return /*#__PURE__*/React.createElement(AuthContext.Provider, {
    value: {
      error,
      isConnecting,
      login,
      client,
      logout,
      isConnected,
      sessionState,
      apiRegion: apiRegion.toLowerCase(),
      isGlobalBan
    }
  }, children);
};
export default AuthContextProvider;
//# sourceMappingURL=AuthProvider.js.map