import json
import com.amazonaws.services.secretsmanager.AWSSecretsManager as AWSSecretsManager ;
import com.amazonaws.services.secretsmanager.AWSSecretsManagerClientBuilder as AWSSecretsManagerClientBuilder;
import com.amazonaws.services.secretsmanager.model.GetSecretValueRequest as GetSecretValueRequest;
import com.amazonaws.services.secretsmanager.model.GetSecretValueResult as GetSecretValueResult;

def get_secret(whid, secret_name):
	logger_name = "%s-Secrets Manager" % (whid)
	logger = system.util.getLogger(logger_name)
	logger.info("Getting secret from Secrets Manager")
	ec2_name = system.tag.readBlocking(["[System]Gateway/SystemName"])[0].value
	secretClient = AWSSecretsManagerClientBuilder.standard().build()
	getSecretValueRequest = GetSecretValueRequest().withSecretId(secret_name)
	
	try:
		    getSecretValueResponse = secretClient.getSecretValue(getSecretValueRequest).getSecretString()
		    secrets_dict = json.loads(getSecretValueResponse)
		    beta_gateway_name = secrets_dict.get("beta-gateway-name")
		    if ec2_name == beta_gateway_name:
		        api_id = secrets_dict.get("beta-api-id")
		        stage = secrets_dict.get("beta-stage")
		        account_id = secrets_dict.get("beta-account-id")
		        function_url = secrets_dict.get("beta-history-function-url")
		    else:
		        api_id = secrets_dict.get("prod-api-id")
		        stage = secrets_dict.get("prod-stage")
		        account_id = secrets_dict.get("prod-account-id")
		    	function_url = secrets_dict.get("prod-history-function-url")
		    return api_id, stage, account_id, function_url
	except:
		AWS.errors.error_handler(whid, "Secrets Manager")
	
	