'''
This script demonstrates importing a repository from a zip file into disy Cadenza
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 posixpath
import urllib.request
from urllib.parse import urljoin
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.xml
    # **/client/apikey
    API_KEY = 'eV9rwLxYyuFs5cSPgueKYG6YLqoiP/yQgDXzehxal83FBXMZiTDCI4S1/MGcvjGv'
    # **/client/encodedSignatureKey
    SECRET = 'LApqIO0HfD7VhOCVLMuVo/JbmTiK8lUgGD+WQMw9kyM0'
    # **/client/clientId (is optional)
    CLIENT_ID = 'api-user'

    # see Cadenza Managment Center for a valid Repo ID
    REPO_ID = 'hK6HtUqLDbvz7rgMNxBk'

    CADENZA_BASE_URL = 'http://localhost:8080'
    BASE_PATH = '/cadenza'

    path = posixpath.join(BASE_PATH, 'public/adminapi/repositories', REPO_ID)

    # build and sign URL using imported functions from cadenza_api_util.py
    url = build_mgmt_api_request_url(urljoin(CADENZA_BASE_URL, path))
    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
            , 'Accept': 'application/zip'
            }

    # path to write the exported repo to
    output_path = f'CadenzaRepo_{REPO_ID}.zip'

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

    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}')
