import json
from jwcrypto.jwk import JWK


class Registration(object):
    _issuer = None
    _client_id = None
    _key_set_url = None
    _key_set = None
    _auth_token_url = None
    _auth_login_url = None
    _tool_private_keys = None
    _tool_public_keys = None

    def __init__(self):
        self._tool_public_keys = []
        self._tool_private_keys = []

    def get_issuer(self):
        return self._issuer

    def set_issuer(self, issuer):
        self._issuer = issuer
        return self

    def get_client_id(self):
        return self._client_id

    def set_client_id(self, client_id):
        self._client_id = client_id
        return self

    def get_key_set(self):
        return self._key_set

    def set_key_set(self, key_set):
        self._key_set = key_set
        return self

    def get_key_set_url(self):
        return self._key_set_url

    def set_key_set_url(self, key_set_url):
        self._key_set_url = key_set_url
        return self

    def get_auth_token_url(self):
        return self._auth_token_url

    def set_auth_token_url(self, auth_token_url):
        self._auth_token_url = auth_token_url
        return self

    def get_auth_login_url(self):
        return self._auth_login_url

    def set_auth_login_url(self, auth_login_url):
        self._auth_login_url = auth_login_url
        return self

    def get_tool_private_key(self, num=0):
        if self._tool_private_keys:
            return self._tool_private_keys[num] if num < len(self._tool_private_keys) else None
        return None

    def get_all_tool_private_keys(self):
        return self._tool_private_keys

    def set_tool_private_key(self, tool_private_key):
        if not tool_private_key:
            raise Exception("Tool Private Key is not set")
        self._tool_private_keys.append(tool_private_key)
        return self

    def get_tool_public_key(self, num=0):
        if self._tool_public_keys:
            return self._tool_public_keys[num] if num < len(self._tool_public_keys) else None
        return None

    def get_all_tool_public_keys(self):
        return self._tool_public_keys

    def set_tool_public_key(self, tool_public_key):
        if not tool_public_key:
            raise Exception("Tool Public Key is not set")
        self._tool_public_keys.append(tool_public_key)
        return self

    def get_jwks(self):
        keys = []
        tool_public_keys = self.get_all_tool_public_keys()
        if tool_public_keys:
            for key in tool_public_keys:
                jwk_obj = JWK.from_pem(key.encode('utf-8'))
                public_jwk = json.loads(jwk_obj.export_public())
                public_jwk['alg'] = 'RS256'
                public_jwk['use'] = 'sig'
                keys.append(public_jwk)
        return keys
