/*-----------------------------------------------------------------*/
/*! 
  \file decodeserver.c
  \brief This server which decodes each node of the OpenMath expression 
         received from the client.
         It prints the received OpenMath expression
         and returns a "procedure completed" message. 

  \author  M. Gastineau 
           Astronomie et Systemes Dynamiques, IMCCE, CNRS, Observatoire de Paris. 

   Copyright, 2008, 2009, 2010, 2011, 2012, M. Gastineau, IMCCE-CNRS
   email of the author : gastineau@imcce.fr

  \bug M. GASTINEAU 20/04/09 : update for SCSCP 1.3
*/
/*-----------------------------------------------------------------*/

/*-----------------------------------------------------------------*/
/* License  of this file :
 This file is "dual-licensed", you have to choose one  of the two licenses 
 below to apply on this file.
 
    CeCILL-C
    	The CeCILL-C license is close to the GNU LGPL.
    	( http://www.cecill.info/licences/Licence_CeCILL-C_V1-en.html )
 
 or CeCILL v2.0
      The CeCILL license is compatible with the GNU GPL.
      ( http://www.cecill.info/licences/Licence_CeCILL_V2-en.html )
 

This library is governed by the CeCILL-C or the CeCILL license under 
French law and abiding by the rules of distribution of free software.  
You can  use, modify and/ or redistribute the software under the terms 
of the CeCILL-C or CeCILL license as circulated by CEA, CNRS and INRIA  
at the following URL "http://www.cecill.info". 

As a counterpart to the access to the source code and  rights to copy,
modify and redistribute granted by the license, users are provided only
with a limited warranty  and the software's author,  the holder of the
economic rights,  and the successive licensors  have only  limited
liability. 

In this respect, the user's attention is drawn to the risks associated
with loading,  using,  modifying and/or developing or reproducing the
software by the user in light of its specific status of free software,
that may mean  that it is complicated to manipulate,  and  that  also
therefore means  that it is reserved for developers  and  experienced
professionals having in-depth computer knowledge. Users are therefore
encouraged to load and test the software's suitability as regards their
requirements in conditions enabling the security of their systems and/or 
data to be ensured and,  more generally, to use and operate it in the 
same conditions as regards security. 

The fact that you are presently reading this means that you have had
knowledge of the CeCILL-C or CeCILL license and that you accept its terms.
*/
/*-----------------------------------------------------------------*/

#include <stdio.h>
#include <stdlib.h>
#include <scscp.h>


static int  processcall(SCSCP_incomingclient *incomingclient, SCSCP_status *status);
static void printelements(SCSCP_xmlnodeptr node, int tab);
static int runserver();


/*-----------------------------------------------------------------*/
/*! start the server and listen on default port */
/*-----------------------------------------------------------------*/
static int runserver()
{
 SCSCP_socketserver server;
 SCSCP_status status = SCSCP_STATUS_INITIALIZER;
 int res;
 SCSCP_incomingclient incomingclient;
 int port = SCSCP_PROTOCOL_DEFAULTPORT;
 
 /*initialization of the server */
 res = SCSCP_ss_init(&server, &status, "MYCASEXAMPLE","1","myid", SCSCP_PROTOCOL_VERSION_1_3, 
                     SCSCP_PROTOCOL_VERSION_1_2, "1.001", NULL); 
               
 /*listen to incoming clients */
 if (res) res = SCSCP_ss_listen(&server, port, 1, &status); 
 
 if (res)
 {
      /* wait for a new client */
      while (SCSCP_ss_acceptclient(&server, &incomingclient, &status))
      {
       printf("a new client is accepted !\n");
       /* loop until an error occurs */
       res=1;
       while (res) res = processcall(&incomingclient, &status);
       printf("close the connection with the client !\n");
       SCSCP_ss_closeincoming(&incomingclient, &status);
      }
 }
 /* destroy the server */
 SCSCP_ss_close(&server, &status);
 res = SCSCP_ss_clear(&server, &status);
 SCSCP_status_clear(&status);
 printf("the server exists\n");
 return 0; 
}

/*-----------------------------------------------------------------*/
/* print the xml tree */
/*-----------------------------------------------------------------*/
static void printelements(SCSCP_xmlnodeptr node, int tab)
{
#define PRINTAB(x) for(j=0; j<x; j++) putchar(' '); 
 SCSCP_xmlattrptr attr;
 const char *name;
 const char *value;
 const char *content;
 int j;
 
 while (node!=NULL)
 {
  PRINTAB(tab); 
  name = SCSCP_xmlnode_getname(node);
  printf ("node : '%s'\n",name?name:"content node");
  
  for (attr = SCSCP_xmlnode_getattr(node); attr!=NULL; attr = SCSCP_xmlattr_getnext(attr))
  {
     SCSCP_xmlattr_getvalue(attr, &name, &value);
     PRINTAB(tab+1); 
     printf ("attribute : '%s '  = '%s'\n",name, value);
  }
  content = SCSCP_xmlnode_getcontent(node);
  if (content)
  {
    PRINTAB(tab+1);
    printf ("content : '%s '\n",content);
  }
  printelements(SCSCP_xmlnode_getchild(node),tab+4);
  node = SCSCP_xmlnode_getnext(node);
 }
 
}


/*-----------------------------------------------------------------*/
/*! process the procedure call */
/*-----------------------------------------------------------------*/
static int  processcall(SCSCP_incomingclient *incomingclient, SCSCP_status *status)
{
 int res, resopt, resret;
 SCSCP_calloptions options;
 SCSCP_returnoptions returnopt;
 SCSCP_msgtype msgtype;
 const char *callid;
 size_t timeusage, memsize;
 int debuglevel;
 SCSCP_option_return returntype;
 
 res = SCSCP_co_init(&options, status);
 res = SCSCP_ro_init(&returnopt, status);
 
 /*wait for a "procedure call" message */
 if (res) res = SCSCP_ss_callrecvheader(incomingclient, &options, &msgtype, status);
 
 if (res)
 {
       /*print call options */
       printf("procedure call options :\n");
       if (!SCSCP_co_get_callid(&options, &callid, status)) 
       {
        callid="N/A client id";
        printf("call id not available\n");
       }
       else
        printf("call id ='%s'\n", callid);
       
       resopt = SCSCP_co_get_runtimelimit(&options, &timeusage, status);
       if (resopt) 
          printf("runtime limit = %lld\n", (long long)timeusage);
       else 
       {
        if (SCSCP_status_is(status)==SCSCP_STATUS_USAGEUNKNOWNRUNTIME)
          printf("runtime limit not available\n");
        else res = 0;
       }
       resopt = SCSCP_co_get_minmemory(&options, &memsize, status);
       if (resopt) 
          printf("minimum memory = %lld\n", (long long)memsize);
       else 
       {
        if (SCSCP_status_is(status)==SCSCP_STATUS_USAGEUNKNOWNMINMEMORY)
          printf("minimum memory not available\n");
        else res = 0;
       }
       
       resopt = SCSCP_co_get_maxmemory(&options, &memsize, status);
       if (resopt) 
          printf("maximum memory = %lld\n", (long long)memsize);
       else 
       {
        if (SCSCP_status_is(status)==SCSCP_STATUS_USAGEUNKNOWNMAXMEMORY)
          printf("maximum memory not available\n");
        else res = 0;
       }
       
       resopt = SCSCP_co_get_debuglevel(&options, &debuglevel, status);
       if (resopt) 
          printf("debug level = %d\n", debuglevel);
       else 
       {
        if (SCSCP_status_is(status)==SCSCP_STATUS_USAGEUNKNOWNDEBUGLEVEL)
          printf("debug level not available\n");
        else res = 0;
       }
       
       resret = SCSCP_co_get_returntype(&options, &returntype, status);
       if (resret) 
          printf("return type = %d\n", (int)returntype);
       else 
       {
        if (SCSCP_status_is(status)==SCSCP_STATUS_USAGEUNKNOWNRETURNTYPE)
          printf("return type not available\n");
        else res = 0;
       }
       
       
       /*print the content of the procedure call */
       printelements(SCSCP_ss_getxmlnode(incomingclient, status), 0);
       
       
       /* reply */
       SCSCP_ro_set_callid(&returnopt, callid, status);
       switch(returntype)
       {
       
        case SCSCP_option_return_object: 
              res = SCSCP_ss_sendcompletedstr(incomingclient, &returnopt,"<OMI>0</OMI>", status); 
              break;

        case SCSCP_option_return_cookie:
              res = SCSCP_ss_sendcompletedstr(incomingclient, &returnopt,"<OMR xref=\"tempobject@localhost:26137\" />", status); 
              break;
              
        case SCSCP_option_return_nothing : 
        default:
              res = SCSCP_ss_sendcompletedstr(incomingclient, &returnopt,"", status); 
              break;
       }
  }
  
  SCSCP_co_clear(&options, status);
  SCSCP_ro_clear(&returnopt, status);
  return res;
}

/*-----------------------------------------------------------------*/
/*! main program */
/*-----------------------------------------------------------------*/
int main(int argc, char *argv[])
{
 return runserver();
}
