package com.sun.identity.saml2.plugins;

import com.sun.identity.saml2.assertion.Attribute;
import com.sun.identity.saml2.common.SAML2Exception;
import com.sun.identity.saml2.common.SAML2SDKUtils;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class DefaultSPAttributeMapper extends DefaultAttributeMapper implements SPAttributeMapper {
   public DefaultSPAttributeMapper() {
      SAML2SDKUtils.DEBUG.message("DefaultSPAttributeMapper.constructor");
   }

   @Override
   public Map<String, Set<String>> getAttributes(List<Attribute> attributes, String userID, String hostEntityID, String remoteEntityID, String realm) throws SAML2Exception {
      if (attributes == null || attributes.isEmpty()) {
         throw new SAML2Exception(SAML2SDKUtils.BUNDLE.getString("nullAttributes"));
      }

      if (hostEntityID == null) {
         throw new SAML2Exception(SAML2SDKUtils.BUNDLE.getString("nullHostEntityID"));
      }

      if (realm == null) {
         throw new SAML2Exception(SAML2SDKUtils.BUNDLE.getString("nullRealm"));
      }

      try {
         Map<String, String> configMap = this.getConfigAttributeMap(realm, hostEntityID, "SPRole");
         if (configMap != null && !configMap.isEmpty()) {
            if (SAML2SDKUtils.DEBUG.messageEnabled()) {
               SAML2SDKUtils.DEBUG.message("DefaultSPAttributeMapper.getAttr:hosted SP attribute map = " + configMap);
            }

            Map<String, Set<String>> map = new HashMap<>();

            for (Attribute attribute : attributes) {
               Set<String> values = new HashSet<>(attribute.getAttributeValueString());
               String attributeName = attribute.getName();
               if ("*".equals(configMap.get("*"))) {
                  map.put(attributeName, values);
               } else {
                  String localAttribute = configMap.get(attributeName);
                  if (localAttribute != null && !localAttribute.isEmpty()) {
                     map.put(localAttribute, values);
                  }
               }
            }

            return map;
         } else {
            if (SAML2SDKUtils.DEBUG.messageEnabled()) {
               SAML2SDKUtils.DEBUG.message("DefaultSPAttributeMapper.getAttr:Configuration map is not defined.");
            }

            return null;
         }
      } catch (SAML2Exception se) {
         SAML2SDKUtils.DEBUG.error("DefaultSPAccountMapper.getAttributes:MetaException", se);
         throw new SAML2Exception(se.getMessage());
      }
   }
}
