#!/usr/bin/env python3
"""Example calling Manhattan Active® API

Manhattan Active® API uses The OAuth 2.0 Authorization Framework as defined here:
    https://datatracker.ietf.org/doc/html/rfc6749

This example uses the resource owner password credentials grant:
    https://datatracker.ietf.org/doc/html/rfc6749#section-4.3
"""

import argparse
import json
import os
import requests


def access_token(client_id, client_secret, token_url, username, password):
    """Return access token for the API using the resource owner password credentials grant

    Conforms to https://datatracker.ietf.org/doc/html/rfc6749#section-4.3

    Must authenticate to token endpoint with client credentials:
    https://datatracker.ietf.org/doc/html/rfc6749#section-3.2.1

    Args:
      client_id (str): client identifier
      client_secret (str): client password
      token_url (str): endpoint to obtain access token
      username (str): the resource owner username
      password (str): the resource owner password

    Returns:
      string: access token

    Raises
       HTTPError:  http error
    """

    # Access Token Request:  https://datatracker.ietf.org/doc/html/rfc6749#section-4.3.2
    data = {"grant_type": "password",
            "username": username, "password": password}
    response = requests.post(token_url, data=data,
                             auth=(client_id, client_secret))
    response.raise_for_status()
    return response.json()["access_token"]


def user(api, token, username):
    """Return user info for username

    Args:
      api (str): root url for api call without a trailing slash
      token (str): access token
      username: user to retreive info

    Returns:
      json: json object with user info

    Raises
       HTTPError:  http error
    """
    url = api + "/organization/api/organization/user/allDetails/userId/" + username

    response = requests.request(
        "GET", url, headers={'Authorization': 'Bearer ' + token}, data={})
    response.raise_for_status()

    return response.json()


if __name__ == "__main__":
    # use envionrment variables or command line arguments
    parser = argparse.ArgumentParser(description="Get user details")
    parser.add_argument(
        '-u', dest='username', default=os.environ.get('ACTIVE_USERNAME'), help="user name")
    parser.add_argument(
        '-p', dest='password', default=os.environ.get('ACTIVE_PASSWORD'), help="password")
    parser.add_argument(
        '-a', dest='api_url', default=os.environ.get('ACTIVE_API_URL'), help="api root url")
    parser.add_argument(
        '-t', dest="token_url", default=os.environ.get('ACTIVE_TOKEN_URL'), help="token endpoint")
    parser.add_argument(
        '-c', dest="client_id", default=os.environ.get('ACTIVE_CLIENT_ID'), help="client id")
    parser.add_argument(
        '-s', dest="client_secret", default=os.environ.get('ACTIVE_CLIENT_SECRET'), help="client secret")
    args = parser.parse_args()

    tok = access_token(args.client_id, args.client_secret,
                       args.token_url, args.username, args.password)

    print(json.dumps(user(args.api_url, tok, args.username), indent=2))
