package com.ajb.common.utils.encryption;

import java.util.Properties;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

import org.apache.commons.lang3.StringUtils;

@Converter
public class JPACryptoConverter implements AttributeConverter<String, String> {

	private static final String secret_property_key = "encryption.key";
	private static final Properties properties = new Properties();
	private static String sensitivekey = null;
	
	static {
		try {
			properties.load(JPACryptoConverter.class.getClassLoader()
					.getResourceAsStream("persistence.properties"));
		} catch (Exception e) {
			properties.put(secret_property_key, "12345678");
		}
		
		sensitivekey = (String)properties.get(secret_property_key);
	}
	
	@Override
	public String convertToDatabaseColumn(String sensitive) {
		DESUtils des;
		String result = "";
		try {
			des = new DESUtils(sensitivekey, "utf-8");
			if (StringUtils.isNotEmpty(sensitive) && StringUtils.isNoneBlank(sensitive))
			{
				result = des.encode(sensitive);
			}
			return result;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

	@Override
	public String convertToEntityAttribute(String sensitive) {
		DESUtils des;
		String result = "";
		try {
			des = new DESUtils(sensitivekey, "utf-8");
			if (StringUtils.isNotEmpty(sensitive) && StringUtils.isNoneBlank(sensitive))
			{
				result = des.decode(sensitive);
			}
			return result;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

}
