#include "client.h"

int Client::monitorStart(OSRTSocket& cstaSocket)
{
   OSOCTET	msgbuf[MAXMSGLEN];
   int len;

   if (trace) {
      printf ("Monitor Start \n" );
   }

   /* Initialize the encoding context */
   ASN1BEREncodeBuffer encodeBuffer (msgbuf, sizeof(msgbuf));

   /* Encode operation argument */
   if ((len = encodeMonitorStartRequest (encodeBuffer)) < 0) 
      return len;

   /* Encode ROSE header on top of encoded argument */
   if ((len = encodeROSERequestHeader (encodeBuffer, len, monitorStart_CODE)) < 0) 
      return len;

   /* Write the encoded message out to the socket */
   sendMessage (cstaSocket, encodeBuffer, len);
   if (trace) {
      printf ("monitor start message sent, len = %d \n", len);
   }

	int stat = receiveCSTAMessage (cstaSocket);
	if (stat != 0) {
		printf ("recvMessage failed, %d \n", stat );
		return stat;
	}
   monitorInitiated = TRUE;
	return 0;
}

int Client::encodeMonitorStartRequest (ASN1BEREncodeBuffer& encodeBuffer)
{
   ASN1T_MonitorStartArgument monStartArgument;
   ASN1C_MonitorStartArgument 
      monStartArgumentC (encodeBuffer, monStartArgument);
   int len;


   char deviceNum[MAX_NUM_SIZE];
   getstring((char *)"Device to monitor :", deviceNum, sizeof(deviceNum));
   if (trace) {
       printf ("encode Monitor Start Request, num %s \n", deviceNum );
   }

   /* To make it simple, we will omit all of the optional fields */

   ASN1T_DeviceID deviceObject;
   deviceObject.deviceIdentifier.t = T_DeviceID_deviceIdentifier_dialingNumber;
   deviceObject.deviceIdentifier.u.dialingNumber = deviceNum;

   monStartArgument.monitorObject.t = T_CSTAObject_deviceObject;
   monStartArgument.monitorObject.u.deviceObject = &deviceObject;

   /* Encode */

   len = monStartArgumentC.Encode();

   if (len < 0) {
      printf ("Encode of MonitorStartArgument failed.\n");
      encodeBuffer.printErrorInfo();
   }

   return len;
}

void Client::processMonitorStartRes(ASN1T_MonitorStartResult& monitorStartRes)
{
   /* Save away the cross reference id.  */
   OSOCTET *xref = new OSOCTET [monitorStartRes.crossRefIdentifier.numocts];
   memcpy(xref, monitorStartRes.crossRefIdentifier.data, 
      monitorStartRes.crossRefIdentifier.numocts);
   mMostRecentMonitor.data = xref;
   mMostRecentMonitor.numocts = monitorStartRes.crossRefIdentifier.numocts;
}
