import json
import jwt
from .AnalyticsHttpClient import AnalyticsHttpClient

from trimble.id._constants import PACKAGE_NAME
from .http_client import HttpClient
import pkg_resources  

class OpenIdKeySetProvider:
    """
    A keyset provider based on the OAuth well known configuration
    """
    def __init__(self, endpointProvider, productName = None):
        """
        Initialize OpenIdKeySetProvider class

        :param endpointProvider: An endpoint provider that provides the URL for the Trimble Identity JSON web keyset endpoint
        :param productName: Product name of the consuming application
        """
        self._endpointProvider = endpointProvider

        self._version = pkg_resources.require(PACKAGE_NAME)[0].version

        AnalyticsHttpClient.SendInitEvent(
            name=self.__class__.__name__, 
            client_name=PACKAGE_NAME, 
            client_version=self._version)

    async def retrieve_keys(self):
        """
        Retrieves an dictionary of named keys
        """

        AnalyticsHttpClient.SendMethodEvent(
            name=f"{self.__class__.__name__}_retrieve_keys", 
            client_name=PACKAGE_NAME, 
            client_version=self._version)

        client = HttpClient('', {})
        result = await client.get_json(await self._endpointProvider.retrieve_jwks_endpoint(), {})
        self._keys = {}
        for jwk in result['keys']:
            kid = jwk['kid']
            self._keys[kid] = jwt.algorithms.RSAAlgorithm.from_jwk(json.dumps(jwk))
        return self._keys