#include "myServer.h"

myPV::myPV (myServer& svrIN,char * nameIn):
	server(svrIN),interest(0)
{
	pvName = new char [strlen(nameIn)+1];
	strcpy(pvName,nameIn);
}

caStatus myPV::read(const casCtx&, gdd &dd)
{
	dd.put(server.value);
	return S_casApp_success;
}

caStatus myPV::write(const casCtx&, gdd &dd)
{
	aitFloat64 newValue;

	dd.get(&newValue, aitEnumFloat64);
	server.value->put(newValue);
	if (interest) postEvent(server.valueEventMask,*value);
	return S_casApp_success;
} 

aitEnum myPV::interestRegister(void)
{
	interest =1;
	return S_casApp_success;
}

void myPV::interestDelete(void) { interest = 0; }

const char *myPV::getName() const { return pvName; }

aitEnum myPV::bestExternalType() const
{
	return aitEnumFloat64;
}

myPV::~myPV(void){delete [] pvName;}

void myPV::destroy(void) { }

int main(int argc, char* argv[]){
	myServer* server;
	int forever=1;

	if(argc<2) {
		fprintf(stderr,"Usage: %s pvName\n",argv[0]);
		return -1;
	}	
	server = new myServer(1,argv[1]);
	osiTime delay(1000u,0u);
	while(forever) {
		fileDescriptorManager.process(delay);
	}
	return 0;
}

myServer::myServer(unsigned pvCountIn,char *nameIn)
{
	pvNameLength = strlen(nameIn);
	pvName = new char [pvNameLength+1];
	strcpy(pvName,nameIn);
	value = new gddScalar(appvalue,aitEnumFloat64);
	value->reference();
	value->put(0);
	value->setStatSevr(0,0);
	mypv = new myPV(*this,pvName);
}

pvExistReturn myServer::pvExistTest(const casCtx&,
	const char* name)
{	
	if(strncmp(name,pvName,pvNameLength)==0)
		return pverExistsHere;
	return pverDoesNotExistHere;
}

pvAttachReturn myServer::pvAttach(const casCtx&,const char* name)
{
	if(strncmp(name,pvName,pvNameLength)==0) return *mypv;
	return NULL;
}

myserver::~myserver(void)
{
	delete [] pvName; 
	value->unreference();
	delete mypv;
}