/*-----------------------------------------------------------------*/
/*! 
  \file decodeserverxx.cpp
  \brief This C++ 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
*/
/*-----------------------------------------------------------------*/

/*-----------------------------------------------------------------*/
/* 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 <cstdio>
#include <cstdlib>
#include <iostream>
#include <scscpxx.h>

using namespace SCSCP;
using namespace std;

static int  processcall(IncomingClient &incomingclient);
static void printelements(Iunfstream& stream, int tab);
static int runserver();


/*-----------------------------------------------------------------*/
/*! start the server and listen on default port */
/*-----------------------------------------------------------------*/
static int runserver()
{
 Server server( "MYCASEXAMPLE","1","myid");
 int res;
 IncomingClient *incomingclient;
 
 /*listen to incoming clients */
 try 
 {
      server.listen(); 
      printf("wait for a client\n");
      
      /* wait for a new client */
      while ((incomingclient = server.acceptclient())!=NULL)
      {
       printf("a new client is accepted !\n");
       /* loop until an error occurs */
       while (processcall(*incomingclient));
       
       printf("close the connection with the client !\n");
       delete incomingclient;
       printf("wait for a client\n");
      }
 }
 catch (Exception e)
 { /* error */
  printf("Exception : %s\n", e.what());
  return 1;
 }
 /* destroy the server */
 server.close();
 printf("the server exists\n");
 return 0; 
}

/*-----------------------------------------------------------------*/
/* print the answer */
/*-----------------------------------------------------------------*/
static void printelements(Iunfstream& stream, int tab)
{
#define PRINTAB(x) for(j=0; j<x; j++) cout <<' '; 
 SCSCP_xmlattrptr attr;
 const char *name;
 const char *value;
 const char *content;
 int j;
 OMS symbol;
 OMR href; 
 OMV var; 
 
 while (!stream.eof())
 {
  PRINTAB(tab); 
  const char *name = stream.get_typename();
  cout << "node : '" << (name?name:"content node") << "'" << endl;
  
  for (Iunfstream::iterator_attr attr = stream.get_attr(); attr.end() ; ++attr)
  {
     PRINTAB(tab+1); 
     cout <<"attribute : '" << attr.get_name() <<"'  = '" << attr.get_value() <<"'"<<endl;
  }
  
  const char * content = stream.get_content();
  int parsechild = 0;
  switch(stream.get_type())
  {
    
    case SCSCP_omtype_OMI : int v; stream>> v; cout << "integer = "<< v <<endl; break;
    case SCSCP_omtype_OMF : double f; stream>> f; cout << "floating-point = "<< f <<endl; break;
    case SCSCP_omtype_OMV :  stream >> var; 
                            cout << "variable = "<< var.get_name() <<endl; 
                            break;
    case SCSCP_omtype_OMS :  stream>> symbol; 
                            cout << "symbol = name : "<< symbol.get_symbolname() << " cd : "<< symbol.get_cdname() <<endl; 
                            break;
    case SCSCP_omtype_OMSTR: const char *s; stream>> s; 
                            cout << "string = '"<< s << "'" <<endl; 
                            break;
    case SCSCP_omtype_OMB:  cout << "OMB" <<endl; parsechild=1; break;
    case SCSCP_omtype_OMFOREIGN: cout << "OMFOREIGN" <<endl;  parsechild=1; break; 
    case SCSCP_omtype_OMA:  cout << "OMA" <<endl;  parsechild=1; break;
    case SCSCP_omtype_OMBIND: cout << "OMBIND" <<endl;  parsechild=1; break;
    case SCSCP_omtype_OMATTR: cout << "OMATTR" <<endl;  parsechild=1; break;
    case SCSCP_omtype_OME:   cout << "OME" <<endl;  parsechild=1; break;
    case SCSCP_omtype_OMATP: cout << "OMATP" <<endl;  parsechild=1; break;
    case SCSCP_omtype_OMOBJ: cout << "OMOBJ" <<endl;  parsechild=1; break;
    case SCSCP_omtype_OMBVAR: cout << "OMBVAR" <<endl;  parsechild=1; break;
                            
    case SCSCP_omtype_OMR:  stream>> href; 
                            cout << "reference =  '"<< href.get_reference() << "'" <<endl; 
                            break;
    case SCSCP_omtype_CONTENT : cout << "content node "<<endl; break;
  }
  
  if (content)
  {
    PRINTAB(tab+1);
    cout <<"content : '" << content <<"'"<<endl;
  }
  
  if (parsechild)
  {
   Iunfstream children = stream.beginOM();
   printelements(children,tab+4);
  }
 }
 
}


/*-----------------------------------------------------------------*/
/*! process the procedure call */
/*-----------------------------------------------------------------*/
static int  processcall(IncomingClient &incomingclient)
{
 int res, resopt, resret;
 SCSCP_msgtype msgtype;
 const char *callid;
 size_t timeusage, memsize;
 int debuglevel;
 SCSCP_option_return returntype;
 
 Server::Computation mytask(incomingclient);
 
 try
 {
      /* wait for a "procedure call" message */
      Iunfstream* inputstream;
      mytask.recv(msgtype, inputstream);
 
       /*print call options */
       printf("procedure call options :\n");
       if (!mytask.get_callid(callid)) 
       {
        callid="N/A client id";
        printf("call id not available\n");
       }
       else
        printf("call id ='%s'\n", callid);
       
       resopt = mytask.get_runtimelimit(timeusage);
       if (resopt) 
          printf("runtime limit = %lld\n", (long long)timeusage);
       else 
       {
          printf("runtime limit not available\n");
       }
       resopt = mytask.get_minmemory(memsize);
       if (resopt) 
          printf("minimum memory = %lld\n", (long long)memsize);
       else 
       {
          printf("minimum memory not available\n");
       }
       
       resopt = mytask.get_maxmemory(memsize);
       if (resopt) 
          printf("maximum memory = %lld\n", (long long)memsize);
       else 
       {
          printf("maximum memory not available\n");
       }
       
       resopt = mytask.get_debuglevel(debuglevel);
       if (resopt) 
          printf("debug level = %d\n", debuglevel);
       else 
       {
          printf("debug level not available\n");
       }
       
       resret = mytask.get_returntype(returntype);
       if (resret) 
          printf("return type = %d\n", (int)returntype);
       else 
       {
        printf("return type not available\n");
       }
       
       
       /*print the content of the procedure call */
       printelements(*inputstream, 0);
       
       
       /* reply */
       switch(returntype)
       {
       
        case SCSCP_option_return_object: 
              mytask.sendcompleted("<OMI>0</OMI>"); 
              break;

        case SCSCP_option_return_cookie:
              mytask.sendcompleted("<OMR xref=\"tempobject@localhost:26137\" />"); 
              break;
              
        case SCSCP_option_return_nothing : 
        default:
              mytask.sendcompleted(""); 
              break;
       }
  res = 1;
  }
 catch (Exception e)
 { /* error */
  printf("error in the procedure call !\nException : %s\n", e.what());
  res= 0;
 }
  
  
  return res;
}

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