//
//pf-msg.c
//
//Handles the conversion to/from a IIP protocol data stream and messages
//
//
//-UserX 2001/11/10

#include "pipeface/raw.h"
#include "misc/global.h"

PipeFace *pfcoreMake(char *pipefacename, char *options) {
	PipeFace *pf = pipefaceMake();
	pipefaceInitFuncs(pf, pfGetMsg, pfPutMsg, NULL);
	pf->IOPipe.status |= PSTATUS_READY;
	return pf;
}


void pfGetMsg(PipeFace *pf, Message **msg) {
	if(pf == NULL) {
		return;
	}
	if(msg == NULL) {
		return;
	}
	*msg = messageMake();
	(*msg)->fromitag = pf->iTag;
	//messageFree(*msg);
	//msg = NULL;

//	switch(pf->PipeFaceType) {
//	case PFT_RAW:
		(*msg)->MessageType = MSGT_RAW;
		//todo: check return error code.
		//pipeRead(&pf->IOPipe, &((*msg)->body), -1);
		if(pipeStatus(&pf->IOPipe) & PSTATUS_READX) {
			pipeGenericRead(&pf->IOPipe);
		}
		if((pipeStatus(&pf->IOPipe) & PSTATUS_READ) && //any data ready?
				(pf->active != 0 || //read data only if there has been previous activity
				pf->retried != -1 || //or this is the out bound side
				retries == 0)) { //or retrying is not available
			pf->active = 1;
			pipeRead(&pf->IOPipe, &((*msg)->body), -1);
		} else {
			messageFree(*msg);
			*msg = NULL;
		}
//		break;
//	}	
}

void pfPutMsg(PipeFace *pf, Message *msg) {
	if(pf == NULL) {
		return;
	}
	if(msg == NULL) {
		return;
	}
//	switch(pf->PipeFaceType) {
//	case PFT_RAW:
		pf->active = 1;
		pipeWrite(&pf->IOPipe, &(msg->body), -1);
//		break;
//	}
	messageFree(msg);
	//msg = NULL;
}
