package com.airlock.iam.oauth2.application.configuration.client;

import com.airlock.iam.elog.api.ELogger;
import com.airlock.iam.elog.api.ELoggerFactory;
import java.util.Collection;
import java.util.Map;
import java.util.Optional;

final class ResourceSelectorHelper {
   private static final ELogger LOG = ELoggerFactory.getLogger(ResourceSelectorHelper.class);

   private ResourceSelectorHelper() {
   }

   static <T> Optional<T> determineResultingValue(Object rawValue, String currentKey, Class<T> type, Map<String, Object> resourceMap) {
      if (rawValue == null) {
         LOG.info("OAuth 2.0 resource with key \"" + currentKey + "\" is null in resource map \"" + resourceMap + "\". Cannot determine value.");
         return Optional.empty();
      } else if (type.isAssignableFrom(rawValue.getClass())) {
         return Optional.of((T)rawValue);
      } else if (rawValue instanceof Collection) {
         rawValue = ((Collection)rawValue).stream().findFirst().orElse(null);
         return determineResultingValue(rawValue, currentKey, type, resourceMap);
      } else {
         LOG.info(
            "OAuth 2.0 resource selector failed to retrieve Object from resource map '"
               + resourceMap
               + "' with key '"
               + currentKey
               + "'. Resource was not of type '"
               + type.getName()
               + "' but of type '"
               + rawValue.getClass().getName()
               + "'"
         );
         return Optional.empty();
      }
   }
}
