/*
 * cs_internal.c
 *
 *  Created on: 14 Mar 2018
 *      Author: development
 */
#include "ssl_mc_private.h"

#include <string.h>
#include <assert.h>

int
mctls_IsMultiContext(
		const SSL* cpt_Ssl)
{
	assert(cpt_Ssl!=NULL);
	return cpt_Ssl->slices_len>0;
}

int
mctls_GetContextIdByName(
		const SSL *cpt_Ssl,
		const char *cps_ContextName,
		CONTEXT_ID /*out*/ *puc_ContextID)
{
	assert(cpt_Ssl!=NULL);
	assert(cps_ContextName!=NULL);
	assert(puc_ContextID!=NULL);

	if(!mctls_IsMultiContext(cpt_Ssl)) {
		return -1;
	}
	for(int i=0;i!=cpt_Ssl->slices_len;++i) {
		if(0==strcmp(cpt_Ssl->slices[i]->purpose,cps_ContextName)) {
			assert(i<256);
			*puc_ContextID= (i&0xFF);
			return 0;
		}
	}
	return mctls_GetDefaultContext(cpt_Ssl,puc_ContextID);
}

int
mctls_GetDefaultContext(
		const SSL *cpt_Ssl,
		CONTEXT_ID /*out*/ *puc_ContextID)
{
	assert(cpt_Ssl!=NULL);
	assert(puc_ContextID!=NULL);

	if(!mctls_IsMultiContext(cpt_Ssl)) {
		return -1;
	}

	for(int i=0;i!=cpt_Ssl->slices_len;++i) {
		if(0==strcmp(cpt_Ssl->slices[i]->purpose,"default")) {
			assert(i<256);
			*puc_ContextID= (CONTEXT_ID) (i&0xFF);
			return 0;
		}
	}
	return -1;

}
int
mctls_GetActiveContext(
		const SSL *cpt_Ssl,
		CONTEXT_ID /*out*/ *puc_CurrentContext)
{
	assert(cpt_Ssl!=NULL);
	if(!mctls_IsMultiContext(cpt_Ssl)) {
		return -1;
	}
	if(puc_CurrentContext!=NULL) { /*allow null, just becomes a nop*/
		/*todo - check this, may need to augment mcTLS
		 * or may need some internal structure to save current context state*/
		*puc_CurrentContext=cpt_Ssl->_slice_id;
	}
	return 0;
}

int
mctls_SetActiveContext(
		SSL *pt_Ssl,
		CONTEXT_ID uc_NewContext,
		CONTEXT_ID *puc_OldContext)
{
	int iGetStatus;

	/*asserts and checking done in the called function here*/
	iGetStatus=mctls_GetActiveContext(pt_Ssl,puc_OldContext);
	if(iGetStatus!=0) return iGetStatus;

	if(pt_Ssl->slices_len>uc_NewContext) {
		pt_Ssl->_slice_id=uc_NewContext;
		return 0;
	} else {
		return -1;
	}
}
