
'''
This script demonstrates downloading data from a disy Cadenza embedding link using
the API key authentication of the Cadenza Management API.

This script imports the functions `build_mgmt_api_request_url` and
`sign_mgmt_api_request_url` from the file `cadenza_api_util.py` provided as part
of the developer documentation. Make sure to have both files in the same folder.
'''
import urllib.request
from urllib.error import HTTPError, URLError
from cadenza_api_util import build_mgmt_api_request_url, sign_mgmt_api_request_url

if __name__ == '__main__':
    # see "accessmanagerapikey" config
    # **/client/apikey
    API_KEY = 'eV9rwLxYyuFs5cSPgueKYG6YLqoiP/yQgDXzehxal83FBXMZiTDCI4S1/MGcvjGv'
    # **/client/encodedSignatureKey
    SECRET = 'LApqIO0HfD7VhOCVLMuVo/JbmTiK8lUgGD+WQMw9kyM0'
    # **/client/clientId (is optional)
    CLIENT_ID = 'api-user'

    # Cadenza embedding link, as copied from the administration dialog of the workbook
    EMBEDDING_URL = 'http://localhost:8080/cadenza/w/messstellenliste?filter.gewaesser=%22...%22'

    # datatype can be one out of 'excel', 'csv', 'json' for embedding links to
    # tables/indicators or 'pdf' for report or jasperreport embeddable content
    DATATYPE = 'csv'

    # if configured in the embeddable content, filters can be assigned in the args
    query = { 'dataType': DATATYPE
            , 'filter.gewaesser': '"Aller"'
            }

    # build and sign URL using imported functions from cadenza_api_util.py
    url = build_mgmt_api_request_url(EMBEDDING_URL, query)
    signature = sign_mgmt_api_request_url(url, SECRET)

    # defining a params dict for the parameters to be sent to the API
    headers = {'X-Api-Key': API_KEY
             , 'X-Client-Id': CLIENT_ID
             , 'X-Request-Signature': signature
             }

    # GET request is needed
    req = urllib.request.Request(url, headers=headers, method='GET')
    print(f'Request Method:      {req.method}')
    print(f'X-Request-Signature: {signature}')

    # filename to write to
    output_path = f'output.{DATATYPE}'

    try:
        with urllib.request.urlopen(req) as response:
            response_body = response.read()
            print(f'Response Code:       {response.status}')
            with open(output_path, 'wb') as output_file:
                output_file.write(response_body)
            print(f'Written {len(response_body)} B to "{output_path}".')
    except HTTPError as e:
        print(f'Response Code:       {e.code}')
        print(f'Message:             {e.reason}')
    except URLError as e:
        print(f'Message:             {e.reason}')
