/**
* Copyright © 2012-2017 by Data Virtuality GmbH
 */
package org.teiid.core.types.basic;

import org.teiid.core.types.BinaryType;
import org.teiid.core.types.DataTypeManager;
import org.teiid.core.types.Transform;
import org.teiid.core.types.TransformationException;

/**
 * 
 * @author Fabio Franco <fabio.franco@datavirtuality.de>
 *
 */
public class StringToBinaryTypeTransform extends Transform {

	public Object transformDirect(Object value) throws TransformationException {
        String string = (String)value;
        
        BinaryType result = null;
        
        /*
         * If string has only hexadecimal values
         * will be converted from hex into byte[].
         * Otherwise String.getBytes() will be
         * directly invoked.
         */
        if (string.length() % 2 == 0 && string.matches("^[0-9a-fA-F]+$")) {
        	result = new BinaryType(hexStringToByteArray(string));
		} else {
			result = new BinaryType(string.getBytes());
		}
        
        return result;
	}
	
	/**
	 * Hex string to byte array.
	 *
	 * @param s the s
	 * @return the byte[]
	 */
	public byte[] hexStringToByteArray(String s) {
	    int len = s.length();
	    byte[] data = new byte[len / 2];
	    for (int i = 0; i < len; i += 2) {
	        data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
	                             + Character.digit(s.charAt(i+1), 16));
	    }
	    return data;
	}

	/**
	 * Type of the incoming value.
	 * @return Source type
	 */
	public Class<?> getSourceType() {
		return DataTypeManager.DefaultDataClasses.STRING;
	}

	/**
	 * Type of the outgoing value.
	 * @return Target type
	 */
	public Class<?> getTargetType() {
		return DataTypeManager.DefaultDataClasses.VARBINARY;
	}
	
	@Override
	public boolean isExplicit() {
		return true;
	}
	
}
