import json


def get_connnection_info_from_args(args, raise_if_none=True):
    """ Returns a dict with the connection info from the arguments. """
    conn_info = None
    raw_conn_info = None
    if args.connection:
        raw_conn_info = args.connection
    elif args.connection_file:
        with args.connection_file as fin:
            raw_conn_info = fin.read()
    elif args.connection_secret:
        conn_info = {"secret_ref": args.connection_secret}

    if not conn_info and raw_conn_info:
        try:
            conn_info = json.loads(raw_conn_info)
        except ValueError as ex:
            raise ValueError(
                "Error while parsing connection info JSON: %s" % str(ex))

    if not conn_info and raise_if_none:
        raise ValueError(
            "No '--connection[-file/secret]' parameter provided.")

    return conn_info