# Copyright (C) 2020-2022 HERE Global B.V. and its affiliate(s).
# All rights reserved.
#
# This software and other materials contain proprietary information
# controlled by HERE and are protected by applicable copyright legislation.
# Any use and utilization of this software and other materials and
# disclosure to any third parties is conditional upon having a separate
# agreement with HERE for the access, use, utilization or disclosure of this
# software. In the absence of such agreement, the use of the software is not
# allowed.

"""
This module contains an :class:`AAAOauth2Api` class to perform oauth API operations.

The HERE API reference documentation used in this module can be found here:
|iam_api_reference|

.. |iam_api_reference| raw:: html

   <a href="https://developer.here.com/documentation/identity-access-management/api-reference-swagger.html">IAM API Reference</a>  # noqa
"""

from typing import Optional

from here.platform.api.base_api import BaseApi
from here.platform.config import ApplicationConfig, PlatformConfig
from here.platform.exceptions import PlatformException
from requests_oauthlib import OAuth1


class AAAOauth2Api(BaseApi):
    """
    This class provides access to HERE platform AAA Oauth2 APIs.
    """

    def __init__(
        self,
        base_url: str,
        platform_config: PlatformConfig,
        application_config: ApplicationConfig,
        proxies: Optional[dict] = None,
    ):
        """
        Instantiate API with auth token.

        :param base_url: base url
        :param platform_config: a mandatory :class:`PlatformConfig` object to provide
            configuration information for the API.
        :param application_config: a mandatory :class:`ApplicationConfig` object to provide
            configuration information for the API.
        :param proxies: an optional proxy configuration. Defaults to the environment proxy
        configuration.
        """
        super(AAAOauth2Api, self).__init__(
            platform_config=platform_config,
            application_config=application_config,
            auth=None,
            proxies=proxies,
        )
        self.base_url = base_url

    def request_scoped_access_token(self, oauth: OAuth1, data: str) -> dict:
        """
        Request scoped access oauth2 token from platform.

        :param oauth: oauth1 configuration.
        :param data: a string which represents request body.
        :return: a json with scoped access token.
        :raises PlatformException: If platform responds with an HTTP error.
        """
        resp = self.post(
            url=self.base_url,
            headers={"Content-Type": "application/x-www-form-urlencoded"},
            data=data,
            auth=oauth,
        )
        if resp.status_code == 200:
            resp_json: dict = resp.json()
            return resp_json
        else:
            raise PlatformException(resp)
