
'''
This script demonstrates calculating intersections with data of a layer in a 
disy Cadenza embedding link. 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 '/area-intersections'
    EMBEDDING_URL = 'http://localhost:8080/cadenza/w/messstellenkarte/area-intersections'

    INPUT_LAYER = [ 'Gewässer', 'Gewässername' ]

    INPUT_GEOMETRY = {
                         'type' : 'Polygon',
                         'coordinates': [ [
                             [ 10.7279808, 52.4598176 ],
                             [ 10.7279808, 52.4211389 ],
                             [ 10.7762982, 52.4211389 ],
                             [ 10.7762982, 52.4598176 ],
                             [ 10.7279808, 52.4598176 ]
                         ] ]
                     }

    # Payload specifies geometry that should be intersected and layer it should be intersected with
    PAYLOAD = {
                         'layerPath': INPUT_LAYER,
                         'geometry': INPUT_GEOMETRY,
                         'useMapSrs': False,
                         'useAutoCorrection': True,
                         'includeGeometryValidationReport': True
                     }


    # 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 intersections
    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()
            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)}')
