package modimapper.mapper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.keycloak.models.ClientSessionContext;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.ProtocolMapperModel;
import org.keycloak.models.UserSessionModel;
import org.keycloak.protocol.oidc.mappers.AbstractOIDCProtocolMapper;
import org.keycloak.protocol.oidc.mappers.OIDCAccessTokenMapper;
import org.keycloak.protocol.oidc.mappers.OIDCAttributeMapperHelper;
import org.keycloak.protocol.oidc.mappers.OIDCIDTokenMapper;
import org.keycloak.protocol.oidc.mappers.UserInfoTokenMapper;
import org.keycloak.provider.ProviderConfigProperty;
import org.keycloak.representations.IDToken;

import jakarta.ws.rs.core.HttpHeaders;

public class DigestMapper extends AbstractOIDCProtocolMapper implements OIDCAccessTokenMapper,
OIDCIDTokenMapper, UserInfoTokenMapper {

  public static final String PROVIDER_ID = "digest-protocol-mapper";

  private static final List<ProviderConfigProperty> configProperties = new ArrayList<>();

  private static final String DIGEST_VALUE = "DigestAuditValue";
  private static final String DIGEST_ALG = "DigestAuditAlgo";
  
  static {
      OIDCAttributeMapperHelper.addTokenClaimNameConfig(configProperties);
      OIDCAttributeMapperHelper.addIncludeInTokensConfig(configProperties, DigestMapper.class);
  }

  @Override
  public String getDisplayCategory() {
      return "Token Mapper";
  }

  @Override
  public String getDisplayType() {
      return "Digest Token Mapper";
  }

  @Override
  public String getHelpText() {
      return "Inserisce l'algoritmo che genera il digest ed il digest stesso nel token";
  }

  @Override
  public List<ProviderConfigProperty> getConfigProperties() {
      return configProperties;
  }

  @Override
  public String getId() {
      return PROVIDER_ID;
  }

  @Override
  protected void setClaim(IDToken token, ProtocolMapperModel mappingModel,
    UserSessionModel userSession, KeycloakSession keycloakSession,
    ClientSessionContext clientSessionCtx) {
	  HttpHeaders httpHeaders = keycloakSession.getContext().getHttpRequest().getHttpHeaders();
	  String digestValue = "";
	  String digestAlg = "";
	  
	  List<String> reqHeaders = httpHeaders.getRequestHeader(DIGEST_VALUE);
	  if (reqHeaders != null && !reqHeaders.isEmpty())
		  digestValue = reqHeaders.get(0);
	  
	  reqHeaders = httpHeaders.getRequestHeader(DIGEST_ALG);
	  if (reqHeaders != null && !reqHeaders.isEmpty())
		  digestAlg = reqHeaders.get(0);
	        
      HashMap<String, String> map = new HashMap<>();
      map.put("alg", digestAlg);
      map.put("value", digestValue);
      
      token.setOtherClaims("digest", map);
  }
}