package com.prime.sony.ecommerce.util;

import java.util.Base64;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.amazonaws.services.secretsmanager.AWSSecretsManager;
import com.amazonaws.services.secretsmanager.AWSSecretsManagerClientBuilder;
import com.amazonaws.services.secretsmanager.model.DecryptionFailureException;
import com.amazonaws.services.secretsmanager.model.GetSecretValueRequest;
import com.amazonaws.services.secretsmanager.model.GetSecretValueResult;
import com.amazonaws.services.secretsmanager.model.InternalServiceErrorException;
import com.amazonaws.services.secretsmanager.model.InvalidParameterException;
import com.amazonaws.services.secretsmanager.model.InvalidRequestException;
import com.amazonaws.services.secretsmanager.model.ResourceNotFoundException;

@Component
public class AWSSecurityConnection {
	private static final Logger log = LoggerFactory.getLogger(AWSSecurityConnection.class);
	
	@Value("${aws.region}")
	private String region;
	

	public AWSSecretsManager getConnection() throws DecryptionFailureException, InternalServiceErrorException,
	InvalidParameterException, InvalidRequestException, ResourceNotFoundException {
		return AWSSecretsManagerClientBuilder.standard().withRegion(region).build();
	}

	public JSONObject getSecreate(String secretName,String region)  {
		this.region=region;
		return getSecreate(secretName); 
	}
	public JSONObject getSecreate(String secretName)  {
		JSONObject secretJsonObj;
		String secret, decodedBinarySecret;
		GetSecretValueRequest getSecretValueRequest = new GetSecretValueRequest().withSecretId(secretName);
		GetSecretValueResult getSecretValueResult = null;

		try {
			getSecretValueResult = getConnection().getSecretValue(getSecretValueRequest);
		} catch (DecryptionFailureException e) {
			throw e;
		} catch (InternalServiceErrorException e) {

			throw e;
		} catch (InvalidParameterException e) {

			throw e;
		} catch (InvalidRequestException e) {

			throw e;
		} catch (ResourceNotFoundException e) {

			throw e;
		}

		if (getSecretValueResult.getSecretString() != null) {
			secret = getSecretValueResult.getSecretString();
			// String username=secret.getString()
			System.out.println(secret);
			secretJsonObj = new JSONObject(secret);
			//String user = jsonObj.getString("user");
			//System.out.println(user);
		} else {
			decodedBinarySecret = new String(
					Base64.getDecoder().decode(getSecretValueResult.getSecretBinary()).array());
			secretJsonObj = new JSONObject(decodedBinarySecret);
		}
		
		return secretJsonObj;
	}

}
