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")

[((20, 4, 27, 5), 'warnings.warn', 'warnings.warn', ({(22, 12, 24, 70): '"""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."""', (26, 8, 26, 26): '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)", False, 'import warnings\n'), ((32, 10, 32, 32), 'requests.get', 'requests.get', ({(32, 23, 32, 31): 'resource'}, {}), '(resource)', False, 'import requests\n'), ((45, 21, 45, 36), 'json.dumps', 'json.dumps', ({(45, 32, 45, 35): 'doc'}, {}), '(doc)', False, 'import json\n'), ((37, 14, 37, 62), 'indexclient.errors.BaseIndexError', 'errors.BaseIndexError', ({(37, 36, 37, 51): 'res.status_code', (37, 53, 37, 61): 'res.text'}, {}), '(res.status_code, res.text)', False, 'from indexclient import errors\n'), ((42, 17, 42, 71), 'json.dumps', 'json.dumps', ({(42, 28, 42, 70): "{'error': 'invalid json payload returned'}"}, {}), "({'error': 'invalid json payload returned'})", False, 'import json\n'), ((43, 14, 43, 60), 'indexclient.errors.BaseIndexError', 'errors.BaseIndexError', ({(43, 36, 43, 51): 'res.status_code', (43, 53, 43, 59): 'reason'}, {}), '(res.status_code, reason)', False, 'from indexclient import errors\n')]