import sys
import json
import logging
import argparse
import warnings

import requests

from indexclient import errors


# DEPRECATED 11/2019 -- interacts with old `/alias/` endpoint.
# For creating aliases for indexd records, prefer using
# the `add_alias` function, which interacts with the new
# `/index/{GUID}/aliases` endpoint.
def info(host, port, name, **kwargs):
    """
    Retrieve info by name.
    """
    warnings.warn(
        (
            "This function is deprecated. For creating aliases for indexd "
            "records, prefer using the `add_alias_for_did` function, which "
            "interacts with the new `/index/{GUID}/aliases` endpoint."
        ),
        DeprecationWarning,
    )
    resource = "http://{host}:{port}/alias/{name}".format(
        host=host, port=port, name=name
    )

    res = requests.get(resource)

    try:
        res.raise_for_status()
    except Exception as err:
        raise errors.BaseIndexError(res.status_code, res.text)

    try:
        doc = res.json()
    except ValueError as err:
        reason = json.dumps({"error": "invalid json payload returned"})
        raise errors.BaseIndexError(res.status_code, reason)

    sys.stdout.write(json.dumps(doc))


def config(parser):
    """
    Configure the info command.
    """
    parser.set_defaults(func=info)

    parser.add_argument("name", help="name of information to retrieve")

[((418, 644), 'warnings.warn', 'warnings.warn', (['"""This function is deprecated. For creating aliases for indexd records, prefer using the `add_alias_for_did` function, which interacts with the new `/index/{GUID}/aliases` endpoint."""', 'DeprecationWarning'], {}), "(\n    'This function is deprecated. For creating aliases for indexd records, prefer using the `add_alias_for_did` function, which interacts with the new `/index/{GUID}/aliases` endpoint.'\n    , DeprecationWarning)\n", (431, 644), False, 'import warnings\n'), ((828, 850), 'requests.get', 'requests.get', (['resource'], {}), '(resource)\n', (840, 850), False, 'import requests\n'), ((1204, 1219), 'json.dumps', 'json.dumps', (['doc'], {}), '(doc)\n', (1214, 1219), False, 'import json\n'), ((935, 983), 'indexclient.errors.BaseIndexError', 'errors.BaseIndexError', (['res.status_code', 'res.text'], {}), '(res.status_code, res.text)\n', (956, 983), False, 'from indexclient import errors\n'), ((1066, 1120), 'json.dumps', 'json.dumps', (["{'error': 'invalid json payload returned'}"], {}), "({'error': 'invalid json payload returned'})\n", (1076, 1120), False, 'import json\n'), ((1135, 1181), 'indexclient.errors.BaseIndexError', 'errors.BaseIndexError', (['res.status_code', 'reason'], {}), '(res.status_code, reason)\n', (1156, 1181), False, 'from indexclient import errors\n')]