package eu.dnetlib.enabling.aas.ctx;

import org.springframework.util.StringUtils;

import eu.dnetlib.enabling.aas.ctx.tools.ICtxRecoder;
import eu.dnetlib.enabling.aas.service.A2Exception;


/**
 * SecurityContext utilities.
 * @author mhorst
 *
 */
public class SecurityContextUtils {

	public static final String NON_SPECIFIED_VERSION = "0";
	
	public static final String INTERNAL_SEC_CTX_DELIMITER = ",";
	
	/**
	 * Extracts version of the coded secCtxChain. Returns String[] where 
	 * String[0] - chain recoder version, 
	 * String[1] - normalized secCtxChain content. 
	 * @param secCtxChain
	 * @return String[] with version and normalized secCtxChain
	 */
	public static String[] tokenizeSecCtxChain(String secCtxChain) throws A2Exception {
		if (secCtxChain==null)
			return null;
		if (!secCtxChain.contains(ICtxRecoder.VERSION_CHAIN_DELIMITER)) {
			String[] result = new String[2];
			result[0] = NON_SPECIFIED_VERSION;
			result[1] = secCtxChain;
			return result;
		} else {
			String[] tokenizedSecCtxChain = StringUtils.tokenizeToStringArray(
					secCtxChain, ICtxRecoder.VERSION_CHAIN_DELIMITER);
			if (tokenizedSecCtxChain.length!=2)
				throw new A2Exception("Invalid SecCtxChain content!");
			return tokenizedSecCtxChain;
		}
	}
	
	/**
	 * Decodes secCtx ids from its String representation. 
	 * Used internally for passing secCtx ids as String content.
	 * @param encodedSecCtxs
	 * @return String[] with decoded secCtx ids
	 */
	public static String[] decodeSecCtxs(String encodedSecCtxs) {
		if (encodedSecCtxs==null)
			return null;
		return StringUtils.tokenizeToStringArray(encodedSecCtxs, INTERNAL_SEC_CTX_DELIMITER);
	}

	/**
	 * Encodes secCtx ids into String representation. 
	 * Used internally for passing secCtx ids as String content.
	 * @param secCtxIds
	 * @return secCtx ids encoded into String representation
	 */
	public static String encodeSecCtxs(String[] secCtxIds) {
		if (secCtxIds==null)
			return null;
		return StringUtils.arrayToDelimitedString(secCtxIds, INTERNAL_SEC_CTX_DELIMITER);
	}
	
}
