package eu.dnetlib.data.graph.model;

import eu.dnetlib.data.proto.TypeProtos.Type;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class DNGFRowKeyDecoder {

	public final static String ID_REGEX = "^[0-9][0-9]\\|.{12}::[a-zA-Z0-9]{32}$";
	/**
	 * logger.
	 */
	private static final Log log = LogFactory.getLog(DNGFRowKeyDecoder.class); // NOPMD by marko on 11/24/08 5:02 PM
	private static final String SEPARATOR = "|";
	private String key;

	private Type type = null;

	private String id = null;

	private DNGFRowKeyDecoder(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 static DNGFRowKeyDecoder decode(final byte[] key) throws IllegalArgumentException {
		return new DNGFRowKeyDecoder(new String(key));
	}

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

	public String getKey() {
		return key;
	}

	public Type getType() {
		return type;
	}

	public String getId() {
		return id;
	}
}
