'''
This script demonstrates deleting a repository from 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
    # **/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/json,application/problem+json;q=0.8'
             }

    # DELETE request is needed
    req = urllib.request.Request(url, headers=headers, method='DELETE')
    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}')
    except HTTPError as e:
        print(f'Response Code:       {e.code}')
        print(f'Message:             {e.reason}')
    except URLError as e:
        print(f'Message:             {e.reason}')
