package eu.dnetlib.data.mapreduce.util;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.io.Text;

import eu.dnetlib.data.proto.TypeProtos.Type;

public class OafRowKeyDecoder {

	/**
	 * logger.
	 */
	private static final Log log = LogFactory.getLog(OafRowKeyDecoder.class); // NOPMD by marko on 11/24/08 5:02 PM

	private static final String SEPARATOR = "|";

	public final static String ID_REGEX = "^[0-9][0-9]\\|.{12}::[a-zA-Z0-9]{32}$";

	private String key;

	private Type type = null;

	private String id = null;

	public static OafRowKeyDecoder decode(final byte[] key) throws IllegalArgumentException {
		return new OafRowKeyDecoder(new String(key));
	}

	public static OafRowKeyDecoder decode(final String key) throws IllegalArgumentException {
		return new OafRowKeyDecoder(key);
	}

	private OafRowKeyDecoder(final String key) throws IllegalArgumentException {
		this.key = key;

		if (!key.matches(ID_REGEX)) {
			String msg = "invalid key: '" + key + "'";
			log.error(msg);
			throw new IllegalArgumentException(msg);
		}

		int tag = Integer.parseInt(StringUtils.substringBefore(key, SEPARATOR));
		this.type = Type.valueOf(tag);
		this.id = StringUtils.substringAfter(key, SEPARATOR);

		// System.out.println(OafRowTypeDecoder.class.getName() +" decoded key: " + split);
	}

	public String getKey() {
		return key;
	}

	public Text getKeyAsText() {
		return new Text(key);
	}

	public Type getType() {
		return type;
	}

	public String getId() {
		return id;
	}
}
