#include "client.h"

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

   if (trace) {
      printf ("answer Call \n" );
   }

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

   /* Encode operation argument */
   if ((len = encodeAnswerCallRequest (encodeBuffer)) < 0) {
      return len;
   }

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

   /* Write the encoded message out to the socket */

   sendMessage (cstaSocket, encodeBuffer, len);
   if (trace) {
      printf ("answer Call msg sent, len = %d \n", len);
   }

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

   return 0;
}

int Client::encodeAnswerCallRequest (ASN1BEREncodeBuffer& encodeBuffer)
{
   if (!callInitiated)
   {
      printf ("Make a call first with MakeCall.\n");
      return -1;
   }

   ASN1T_AnswerCallArgument answerCallArg;
   ASN1C_AnswerCallArgument answerCallArgC(encodeBuffer, answerCallArg);
   int len;

   char deviceNum[MAX_NUM_SIZE];
   getstring((char *)"Device to lift :", deviceNum, sizeof(deviceNum));

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

   answerCallArg.callToBeAnswered.t = T_ConnectionID_both;
   ASN1T_ConnectionID_both cidBoth;
   cidBoth.callID = mMostRecentCall.u.both->callID;
   cidBoth.deviceID.t = T_LocalDeviceID_staticID;
   ASN1T_DeviceID deviceID;
   deviceID.m.mediaCallCharacteristicsPresent = 0;
   deviceID.deviceIdentifier.t = T_DeviceID_deviceIdentifier_dialingNumber;
   deviceID.deviceIdentifier.u.dialingNumber = deviceNum;
   cidBoth.deviceID.u.staticID = &deviceID;
   answerCallArg.callToBeAnswered.u.both = &cidBoth;

   /* Encode */

   len = answerCallArgC.Encode();

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

   return len;
}

void Client::processAnswerCallRes(ASN1T_AnswerCallResult& answerCallRes)
{
   //TODO: user action for PBX response to answer call
}
