package eu.dnetlib.enabling.aas.ctx.tools;



/**
 * Simple decoding and encoding secCtxId from and into a secCtxChain.
 * This implementation doesn't use publ/private key pair therefore 
 * it requires only the currentChain and secCtxId.
 * @author mhorst
 *
 */
public class SimpleContextRecoder implements ICtxRecoder {
	
	public static final String VERSION = "0";
	
	public static final char MAJOR_CHUNK_DELIMITER = ',';

	/* (non-Javadoc)
	 * @see eu.dnetlib.enabling.aas.ctx.tools.ICtxRecoder#decode(eu.dnetlib.enabling.aas.ctx.tools.CodingContext, java.lang.String, byte[])
	 */
	public DecodingResponse decode(CodingContext ctx, String currentChain,
			byte[] otherPubKey) {
		if (currentChain==null)
			return null;
		DecodingResponse response = new DecodingResponse();
		int index = currentChain.indexOf(MAJOR_CHUNK_DELIMITER);
		if (index==-1) {
			response.chain = null;
			response.secCtxId = currentChain;
		} else if (index==currentChain.length()-1) {
			response.chain = null;
			response.secCtxId = currentChain.substring(0, index);
		} else {
			response.chain = currentChain.substring(index+1);
			response.secCtxId = currentChain.substring(0,index);
		}
		return response;
	}

	/* (non-Javadoc)
	 * @see eu.dnetlib.enabling.aas.ctx.tools.ICtxRecoder#encode(eu.dnetlib.enabling.aas.ctx.tools.CodingContext, java.lang.String, byte[])
	 */
	public String encode(CodingContext ctx, String currentChain,
			byte[] otherPubKey) {
		if (ctx==null || ctx.secCtxId==null)
			return null;
		if (currentChain==null)
			return ctx.secCtxId;
		else
			return currentChain + MAJOR_CHUNK_DELIMITER + ctx.secCtxId;
	}
	
	/* (non-Javadoc)
	 * @see eu.dnetlib.enabling.aas.ctx.tools.ICtxRecoder#identify()
	 */
	public String identify() {
		return VERSION;
	}

	/* (non-Javadoc)
	 * @see eu.dnetlib.enabling.aas.ctx.tools.ICtxRecoder#appendVersionPrefix(java.lang.String)
	 */
	public String appendVersionPrefix(String secCtxChain) {
		if (secCtxChain!=null)
			return VERSION + VERSION_CHAIN_DELIMITER + secCtxChain;
		else
			return VERSION + VERSION_CHAIN_DELIMITER;
	}

}
