
import os
import sys


from commonfunctions.core import getResponseFromURL
from commonfunctions.core import getParameter
from commonfunctions.core import getLocalLogger


def getSecretsDictFromKeyMakerResponse(jresponse):
    elementList = jresponse["nonkeys"]
    keyMakerSecretsDict = {}
    for element in elementList:
        secretItem = element['nonkey']
        secretName = secretItem['name']
        encodedKeyData = secretItem['encoded_key_data']
        keyData = base64ToString(value=encodedKeyData)
        keyMakerSecretsDict[secretName] = keyData
    return keyMakerSecretsDict


#%%

def getKeyMakerSecretsDict(serverDomain, keyMakerToken, loggingPrefix=None):
    hostname = getParameter('HOST_HOSTNAME')
    locallogger = getLocalLogger(localloggername='getFilePath', rootFileName=__name__, loggingPrefix=loggingPrefix)
    if hostname in ["L-SIN-42650223", 'integration-server-dev-1']:
        # Dev Key Maker
        keyMakerURL = f"https://{serverDomain}/kmsapi/v1/keyobject/all"
    else:
		# Prod Key Maker
        keyMakerURL = f"https://{serverDomain}:21358/kmsapi/v1/keyobject/all"
    method = "GET"
    headers = {
			"X-KM-APP-CONTEXT" : keyMakerToken,
	}
    response = getResponseFromURL(url=keyMakerURL, method=method, headers=headers, auth=None,  proxies=None, data=None, json=None, params=None, cookies=None, verify=False, timeout=120, session=None, loggingPrefix=None, responseEncoding=None, maxRetry=1, sleepCodeList=None, sleepSeconds=300, returnJson=False)
    if response.status_code != 200:
        locallogger.error(f"Response Code '{response.status_code}' received.  Exiting....")
        sys.exit(1)
    jresponse = response.json()
    keyMakerSecretsDict = getSecretsDictFromKeyMakerResponse(jresponse=jresponse)
    return 	keyMakerSecretsDict














