// 
// Decompiled by Procyon v0.6.0
// 

package com.nimbusds.jose.proc;

import com.nimbusds.jose.jwk.JWK;
import com.nimbusds.jose.jwk.JWKSelector;
import com.nimbusds.jose.jwk.KeyType;
import com.nimbusds.jose.jwk.KeyUse;
import com.nimbusds.jose.jwk.JWKMatcher;
import com.nimbusds.jose.jwk.source.RemoteJWKSet;
import java.net.URL;
import com.nimbusds.jose.KeySourceException;
import java.util.Collections;
import java.security.Key;
import java.util.List;
import com.nimbusds.jose.JWSHeader;
import java.util.Iterator;
import java.util.HashMap;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.JWSAlgorithm;
import java.util.Map;

public class JWSAlgorithmFamilyJWSKeySelector<C extends SecurityContext> extends AbstractJWKSelectorWithSource<C> implements JWSKeySelector<C>
{
    private final Map<JWSAlgorithm, JWSKeySelector<C>> selectors;
    
    public JWSAlgorithmFamilyJWSKeySelector(final JWSAlgorithm.Family jwsAlgFamily, final JWKSource<C> jwkSource) {
        super(jwkSource);
        this.selectors = new HashMap<JWSAlgorithm, JWSKeySelector<C>>();
        for (final JWSAlgorithm jwsAlg : jwsAlgFamily) {
            this.selectors.put(jwsAlg, new JWSVerificationKeySelector<C>(jwsAlg, jwkSource));
        }
    }
    
    @Override
    public List<? extends Key> selectJWSKeys(final JWSHeader header, final C context) throws KeySourceException {
        final JWSKeySelector<C> selector = this.selectors.get(header.getAlgorithm());
        if (selector == null) {
            return Collections.emptyList();
        }
        return selector.selectJWSKeys(header, context);
    }
    
    public static <C extends SecurityContext> JWSAlgorithmFamilyJWSKeySelector<C> fromJWKSetURL(final URL jwkSetURL) throws KeySourceException {
        final JWKSource<C> jwkSource = new RemoteJWKSet<C>(jwkSetURL);
        return fromJWKSource(jwkSource);
    }
    
    public static <C extends SecurityContext> JWSAlgorithmFamilyJWSKeySelector<C> fromJWKSource(final JWKSource<C> jwkSource) throws KeySourceException {
        final JWKMatcher jwkMatcher = new JWKMatcher.Builder().publicOnly(true).keyUses(KeyUse.SIGNATURE, null).keyTypes(KeyType.RSA, KeyType.EC).build();
        final List<? extends JWK> jwks = jwkSource.get(new JWKSelector(jwkMatcher), null);
        for (final JWK jwk : jwks) {
            if (KeyType.RSA.equals(jwk.getKeyType())) {
                return new JWSAlgorithmFamilyJWSKeySelector<C>(JWSAlgorithm.Family.RSA, jwkSource);
            }
            if (KeyType.EC.equals(jwk.getKeyType())) {
                return new JWSAlgorithmFamilyJWSKeySelector<C>(JWSAlgorithm.Family.EC, jwkSource);
            }
        }
        throw new KeySourceException("Couldn't retrieve JWKs");
    }
}
