package com.sun.identity.shared.configuration;

import com.sun.identity.saml2.common.SAML2Utils;
import java.lang.reflect.InvocationTargetException;
import java.util.Properties;

public final class SystemPropertiesManager {
   private static ISystemProperties systemProperties;
   private static final String PARAM_SYS_CONFIG = "com.sun.identity.systemconfiguration";

   private static boolean instantiateDefinedProvider() {
      boolean succeeded = true;
      String param = System.getProperty("com.sun.identity.systemconfiguration");
      if (param != null) {
         try {
            Class<?> clazz = Class.forName(param);
            systemProperties = (ISystemProperties)clazz.getDeclaredConstructor().newInstance();
         } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | ClassCastException | InvocationTargetException | NoSuchMethodException e) {
            SAML2Utils.DEBUG.warning("Failed to instantiate OpenSSO system properties provider: " + param, e);
            succeeded = false;
         }
      }

      return succeeded;
   }

   private static boolean instantiateProvider(String providerClassName) {
      try {
         Class<?> clazz = Class.forName(providerClassName);
         systemProperties = (ISystemProperties)clazz.getDeclaredConstructor().newInstance();
         return true;
      } catch (ClassNotFoundException e) {
         return true;
      } catch (InstantiationException | IllegalAccessException | ClassCastException | InvocationTargetException | NoSuchMethodException e) {
         SAML2Utils.DEBUG.warning("Failed to instantiate OpenSSO system properties provider: " + providerClassName, e);
         return false;
      }
   }

   private SystemPropertiesManager() {
   }

   public static ISystemProperties getSystemProperties() {
      return systemProperties;
   }

   public static String get(String key) {
      return systemProperties != null ? systemProperties.get(key) : null;
   }

   public static String get(String key, String defaultValue) {
      String value = get(key);
      return value != null && !value.trim().isEmpty() ? value : defaultValue;
   }

   public static void initializeProperties(Properties properties) {
      if (systemProperties != null) {
         systemProperties.initializeProperties(properties);
      }
   }

   public static void initializeProperties(String propertyName, String propertyValue) {
      if (systemProperties != null) {
         systemProperties.initializeProperties(propertyName, propertyValue);
      }
   }

   static {
      if (instantiateDefinedProvider()
         && systemProperties == null
         && instantiateProvider("com.sun.identity.configuration.FedSystemProperties")
         && systemProperties == null
         && instantiateProvider("com.sun.identity.configuration.SystemProperties")
         && systemProperties == null) {
         instantiateProvider("com.sun.identity.configuration.FedLibSystemProperties");
      }
   }
}
