package com.sun.identity.plugin.session;

import com.sun.identity.common.SystemConfigurationUtil;
import com.sun.identity.shared.debug.Debug;
import com.sun.identity.shared.locale.Locale;
import jakarta.annotation.Nullable;
import java.lang.reflect.InvocationTargetException;
import java.util.ResourceBundle;

public final class SessionManager {
   private static final String PROP_SESSION_IMPL_CLASS = "com.sun.identity.plugin.session.class";
   private static final Debug DEBUG = Debug.getInstance("libPlugins");
   private static final ResourceBundle BUNDLE = Locale.getInstallResourceBundle("libSessionProvider");
   private static final SessionProvider SESSION_PROVIDER = instantiateSessionProvider();

   @Nullable
   private static SessionProvider instantiateSessionProvider() {
      String sessionClass = SystemConfigurationUtil.getProperty("com.sun.identity.plugin.session.class");
      if (sessionClass != null && !sessionClass.isEmpty()) {
         try {
            return (SessionProvider)Class.forName(sessionClass).getDeclaredConstructor().newInstance();
         } catch (IllegalAccessException | InstantiationException | InvocationTargetException | NoSuchMethodException iae) {
            DEBUG.error("SessionManager static block: Failed creating SessionProvider instance: " + sessionClass, iae);
         } catch (ClassNotFoundException cnfe) {
            DEBUG.error("SessionManager static block: Unable to find class " + sessionClass, cnfe);
         }
      } else {
         DEBUG.error("SessionManager static block: the property com.sun.identity.plugin.session.class is not set.");
      }

      return null;
   }

   public static SessionProvider getProvider() throws SessionException {
      if (SESSION_PROVIDER == null) {
         throw new SessionException(BUNDLE.getString("nullSessionProvider"));
      } else {
         return SESSION_PROVIDER;
      }
   }
}
