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

import com.airlock.iam.oauth2.domain.service.client.resource.OAuth2ResourceSelector;
import com.airlock.iam.plugin.api.annotation.config.Plugin;
import com.airlock.iam.plugin.api.annotation.license.PluginLicenseRestriction;
import com.airlock.iam.plugin.api.annotation.property.StringProperty;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.util.Map;
import java.util.Optional;

@Plugin(
   description = "Plugin to select a specific resource out of a response given its key. If the attribute contains multiple values, the first is used.",
   displayName = "OAuth 2.0 Simple Resource Selector"
)
@PluginLicenseRestriction(moduleAffiliation = "OAuthClient")
public final class OAuth2SimpleResourceSelector implements OAuth2ResourceSelector {
   @StringProperty(
      description = "Key associated with the object to be selected.",
      optional = false,
      suggestedValues = {"sub", "iss", "aud", "iat", "exp", "username"}
   )
   private String key;

   @Override
   public <T> Optional<T> retrieveResource(Map<String, Object> resourceMap, Class<T> type) {
      Object rawValue = resourceMap.get(this.key);
      return ResourceSelectorHelper.determineResultingValue(rawValue, this.key, type, resourceMap);
   }

   @SuppressFBWarnings(justification = "generated code")
   public static OAuth2SimpleResourceSelector.OAuth2SimpleResourceSelectorBuilder builder() {
      return new OAuth2SimpleResourceSelector.OAuth2SimpleResourceSelectorBuilder();
   }

   @SuppressFBWarnings(justification = "generated code")
   public OAuth2SimpleResourceSelector(String key) {
      this.key = key;
   }

   @SuppressFBWarnings(justification = "generated code")
   public OAuth2SimpleResourceSelector() {
   }

   @SuppressFBWarnings(justification = "generated code")
   public static class OAuth2SimpleResourceSelectorBuilder {
      @SuppressFBWarnings(justification = "generated code")
      private String key;

      @SuppressFBWarnings(justification = "generated code")
      OAuth2SimpleResourceSelectorBuilder() {
      }

      @SuppressFBWarnings(justification = "generated code")
      public OAuth2SimpleResourceSelector.OAuth2SimpleResourceSelectorBuilder key(String key) {
         this.key = key;
         return this;
      }

      @SuppressFBWarnings(justification = "generated code")
      public OAuth2SimpleResourceSelector build() {
         return new OAuth2SimpleResourceSelector(this.key);
      }

      @SuppressFBWarnings(justification = "generated code")
      @Override
      public String toString() {
         return "OAuth2SimpleResourceSelector.OAuth2SimpleResourceSelectorBuilder(key=" + this.key + ")";
      }
   }
}
