# python standard lib 
import hashlib
# python standard lib 
import hmac
import time
import requests
from requests_toolbelt.multipart.encoder import MultipartEncoder
import base64
import urllib.parse

# see accessmanagerapikey-config.xml
apikey = "9e9a4776f72e2d177492e7853a0b744a5c27e4e184cc436faca4885f38b87c42" # **/client/apikey
secret = "oma4gWkKB0SaI1yWogFs2Fest/pNlpWJE2dUNfGqOpc="                     # **/client/encodedSignatureKey
clientid = 'api-user'                                                       # **/client/clientId (is optional)

repositorySchemaId="REPO_DB"                                                # needed if more than one Repo-DB is defined in repositoryList.xml 

cadenzabaseurl ="http://localhost:8000"
basePath = "/cadenza"

# unix epochtime in millisecond
epochetime=int(time.time() * 1000)
query = { 'repositorySchemaId': str(repositorySchemaId),
          'requestTimestamp': str(epochetime) }

pathAndQuery = urllib.parse.quote(basePath + "/public/adminapi/repositories") \
             + "?" \
             + urllib.parse.urlencode(query)
URL = cadenzabaseurl + pathAndQuery

# secret is base64 encoded, hmac needs a byte array
decodedSecret = base64.b64decode(secret)
hmacHash = hmac.new(decodedSecret, pathAndQuery.encode(), hashlib.sha256).digest()

# hash is a byte array, encode with base64
signature = base64.b64encode(hmacHash).decode()

# Specify the repo-file and URL
file_path = 'path/repository.zip'

# Prepare the multipart, the MultipartEncoder is used for the boundary handling
multipart = MultipartEncoder(
  fields = 
    { 'file': ('repository.zip', open(file_path, 'rb').read(), 'application/zip')
    }
)

# defining a params dict for the parameters to be sent to the API
headers = {
   'X-Api-Key': apikey
  , 'X-Client-Id': clientid
  , 'X-Request-Signature': signature
  , 'Content-Type': multipart.content_type
  , 'Accept': 'application/json' 
  }


# post request is needed
r = requests.post(URL, data=multipart, headers=headers)

print("RequestURL:          " + str(r.url))
print("SignaturURL:         " + pathAndQuery)
print("X-Request-Signature: " + signature)
print("Response Code:       " + str(r))
print("Response:            " + r.text)