package pt.link.crypto;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class CryptoManager {
	static Log log = LogFactory.getLog(CryptoManager.class);
	
	public static byte[] keyBytes = {-0x39,-0x27,0x73,-0x20,-0x4a,0x4,0x61,-0x9};
	
	private String merchantCardNumber = null;
	/**
	 * @return Returns the merchantCardNumber.
	 */
	public String getMerchantCardNumber() throws CryptoException{
		String encrypted = UtilProperties.getPropertyValue(secretsResource, "merchant.number", loaderClass);
		try {
			merchantCardNumber = CryptoUtils.deCipher(encrypted, keyBytes);
		} catch (CryptoException e) {
			String errorMessage = "Exception caught while initializing CryptoManager";
			log.error(errorMessage, e);
			throw new CryptoException(e);
		}
		return merchantCardNumber;
	}

	/**
	 * @param merchantCardNumber The merchantCardNumber to set.
	 */
	public void setMerchantCardNumber(String merchantCardNumber) {
		this.merchantCardNumber = merchantCardNumber;
	}
	
	
	
	private static CryptoManager _instance = null;
	public static CryptoManager getInstance() throws CryptoException{
		if(_instance == null){
			_instance = new CryptoManager();
			//_instance.init();
		}
		return _instance;
	}
	
	private Class loaderClass = CryptoException.class;
	public void setLoaderClass(Class clazz){
		loaderClass = clazz;
	}
	
	private String secretsResource ="3DS.properties";
	public void setSecretResources(String resource){
		secretsResource = resource; 
	}
	
//	private void init() throws CryptoException{
//		
//		String encrypted = UtilProperties.getPropertyValue(secretsResource, "merchant.number", loaderClass);
//		try {
//			merchantCardNumber = CryptoUtils.deCipher(encrypted, keyBytes);
//		} catch (CryptoException e) {
//			String errorMessage = "Exception caught while initializing CryptoManager";
//			log.error(errorMessage, e);
//			throw new CryptoException();
//		}
//	}
	
	public SecurityElement doHmacSha1Cryptogram(byte[] inputText) throws CryptoException {
		try {
			SecretKeySpec key = new SecretKeySpec(getMerchantCardNumber()
					.getBytes("UTF8"), "HmacSHA1");
			Mac mac = Mac.getInstance(key.getAlgorithm());
			mac.init(key);
			byte[] digest = mac.doFinal(inputText);
			return new SecurityElement(digest);
		} catch(CryptoException ce){
			throw ce;
		} catch (Exception e) {
			String errorMessage = "Exception cauhth while producing digest";
			log.error(errorMessage, e);
			throw new CryptoException(e);
		}
	}
}
