'''
This script demonstrates retrieving an object's object information from a layer 
in a disy Cadenza map view (identified through a disy Cadenza embedding link) by 
its id. The call is authenticated 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
import json
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 from the administration dialog of the workbook, added '/objectinfo'
    EMBEDDING_URL = 'http://localhost:8080/cadenza/w/messstellenkarte/objectinfo'

    # Payload specifies ids of objects of which info should be retrieved and layer it should be retrieved from
    INPUT_LAYER = [ 'Messungen Fließgewässerchemie' ]
    INPUT_IDS = [ [ 48132180 ] ]
    PAYLOAD = {
                   'layerPath': INPUT_LAYER,
                   'objectIds': INPUT_IDS,
              }

    # if configured in the embeddable content, filters can be assigned in the args
    query = { 
                '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)

    # encode payload
    jsondata = json.dumps(PAYLOAD)
    jsondataasbytes = jsondata.encode('utf-8')   # needs to be bytes

    # 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
             , 'Accept': 'application/json,application/problem+json;q=0.8'
             , 'Content-Type': 'application/json'
             , 'Content-Length': len(jsondataasbytes)
             }

    # POST request for object information
    req = urllib.request.Request(url, headers=headers, method='POST')
    print(f'Request Method:      {req.method}')
    print(f'X-Request-Signature: {signature}')

    try:
        with urllib.request.urlopen(req, jsondataasbytes) as response:
            response_body = response.read().decode('utf-8')
            response_pretty = json.dumps(json.loads(response_body), indent=2)
            print(f'Response Code:       {response.status}')
            print(f'Response Body:       {response_pretty}')
    except HTTPError as e:
        print(f'Response Code:       {e.code}')
        print(f'Reason:              {e.reason}')
        print(f'Message:             {json.dumps(json.loads(e.read().decode()), indent=2)}')
    except URLError as e:
        print(f'Reason:              {e.reason}')
        print(f'Message:             {json.dumps(json.loads(e.read().decode()), indent=2)}')
