/*****************************************************************
Copyright (c) 1999 Torben Weis <weis@kde.org>
Copyright (c) 2000 Matthias Ettrich <ettrich@kde.org>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

******************************************************************/
#include <qdom.h>
#include <qfile.h>
#include <qtextstream.h>
#include <qstring.h>
#include <qregexp.h>

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include "main.h"


QString javaType(QString type)
{
    if (type == "bool")
	return "boolean";
    if (type == "QString")
	return "String";
    if (type == "QCString")
	return "String";
    if (type == "QStringList")
	return "String[]"; 
    if (type == "short int")
	return "short";
    if (type == "long int")
	return "int";

    return type;
}


QString javaRightAttribute(QString attr)
{
  if (attr == "&")
    return QString::null;

  return "!!!NOT IMPLEMENTED: "  + attr;  
}


QString javaLeftAttribute(QString attr)
{
  if (attr == "const")
    return QString::null;

  return "!!!NOT IMPLEMENTED: "  + attr;  
}


QString javaQualifier(QString qual)
{
  if (qual == "const")
    return QString::null;

  return "!!!NOT IMPLEMENTED: " + qual;
}


QString underscore(QString in)
{
  return in.replace(QRegExp(" "), "_");
}


QString defValue(QString type)
{
  if (type == "bool")
    return "false";
  if (type == "QString")
    return "null";
  if (type == "QStringList")
    return "null";
  if (type == "DCOPRef")
      return "null";
  if (type == "QCString")
      return "null";

  return "0";
}


/**
 * Writes the stub implementation
 */
void generateStubImpl( const QString& idl, const QString& package, const QString& filename, QDomElement de )
{
  QFile impl( filename );
  if ( !impl.open( IO_WriteOnly ) )
    qFatal("Could not write to %s", filename.latin1() );

  QTextStream str( &impl );

  str << "/****************************************************************************" << endl;
  str << "**" << endl;
  str << "** DCOP Stub Implementation created by dcopidl2java from " << idl << endl;
  str << "**" << endl;
  str << "** WARNING! All changes made in this file will be lost!" << endl;
  str << "**" << endl;
  str << "*****************************************************************************/" << endl;
  str << endl;

  if (!package.isEmpty())
    str << endl << "package " << package << ";" << endl << endl;
  
  str << endl << "import java.io.*;" << endl;
  str << "import org.kde.DCOP.*;" << endl;
  str << endl << endl;

  QDomElement e = de.firstChild().toElement();
  for( ; !e.isNull(); e = e.nextSibling().toElement() ) {
    if ( e.tagName() == "CLASS" ) {
      QDomElement n = e.firstChild().toElement();
      ASSERT( n.tagName() == "NAME" );
      QString className = n.firstChild().toText().data() + "_stub";
	
      // find dcop parent ( rightmost super class )
      QString DCOPParent;
      QDomElement s = n.nextSibling().toElement();
      for( ; !s.isNull(); s = s.nextSibling().toElement() ) {
	if ( s.tagName() == "SUPER" )
	  DCOPParent = s.firstChild().toText().data();
      }
	
      // Start class definition
      str << "class " << className;

      if ( DCOPParent.isEmpty() || DCOPParent == "DCOPObject" )
	str << " extends Stub" << endl;
      else
	str << " extends " << DCOPParent << endl;

      str << "{" << endl;

      // Write constructor
      str << "  public " << className << "(String app, String obj)" << endl;
      str << "  {" << endl << "    super(app, obj);" << endl << "  }" << endl;
      str << endl;

      // Write marshalling code
      s = e.firstChild().toElement();
      for( ; !s.isNull(); s = s.nextSibling().toElement() ) {
	if ( s.tagName() == "FUNC" ) {
	  QDomElement r = s.firstChild().toElement();
	  ASSERT( r.tagName() == "TYPE" );
	  QString result = r.firstChild().toText().data();
	  str << "  public ";
	  bool async = result == "ASYNC";
	  if ( async)
	    result = "void";
	  if ( r.hasAttribute( "qleft" ) )
	    str << "  " << javaLeftAttribute(r.attribute("qleft")) << " ";
	  str << javaType(result);
	  if ( r.hasAttribute( "qright" ) )
	    str << "  " << javaRightAttribute(r.attribute("qright")) << " ";
	  else
	    str << " ";

	  r = r.nextSibling().toElement();
	  ASSERT ( r.tagName() == "NAME" );
	  QString funcName = r.firstChild().toText().data();
	  str << funcName << "(";

	  QStringList args;
	  QStringList argtypes;
	  bool first = TRUE;
	  r = r.nextSibling().toElement();
	  for( ; !r.isNull(); r = r.nextSibling().toElement() ) {
	    if ( !first )
	      str << ", ";
	    first = FALSE;
	    ASSERT( r.tagName() == "ARG" );
	    QDomElement a = r.firstChild().toElement();
	    ASSERT( a.tagName() == "TYPE" );
	    if ( a.hasAttribute( "qleft" ) )
	      str << javaLeftAttribute(a.attribute("qleft")) << " ";
	    argtypes.append(a.firstChild().toText().data());
	    str << javaType(argtypes.last());
	    if ( a.hasAttribute( "qright" ) )
	      str << javaRightAttribute(a.attribute("qright")) << " ";
	    else
	      str << " ";
	    args.append(QString("arg") + QString::number(args.count())) ;
	    str << args.last();
	  }
	  str << ")";

	  if ( s.hasAttribute("qual") )
	    str << " " << javaQualifier(s.attribute("qual"));
	  str << endl;
		
	  str << "  {" << endl ;

	  funcName += "(";
	  first = TRUE;
	  for( QStringList::Iterator it = argtypes.begin(); it != argtypes.end(); ++it ){
	    if ( !first )
	      funcName += ",";
	    first = FALSE;
	    funcName += *it;
	  }
	  funcName += ")";
		
	  if ( async ) {
	    str << "    ByteArrayOutputStream bs = new ByteArrayOutputStream();" << endl;
	    if ( !args.isEmpty() ) {
	      str << "    DataOutputStream os = new DataOutputStream(bs);" << endl;
	      str << "    try" << endl;
	      str << "    {" << endl;

	      QStringList::Iterator itt, ita;
	      for (itt = argtypes.begin(), ita = args.begin(); itt != argtypes.end(); ++itt, ++ita)
		str << "      write_" << *itt << "(os, " << *ita << ");" << endl;
	    }
	    str << "    client().send(app(), obj(), \"" << funcName << "\", bs.toByteArray());" << endl;
	    str << "    setStatus(CallSucceeded);" << endl;
	    if (!args.isEmpty())
	      {
		str << "    }" << endl;
		str << "    catch (java.io.IOException e)" << endl;
		str << "    {" << endl;
		str << "      callFailed();" << endl;
		str << "    }" << endl;
	      }
	  } else {
		
	    if ( result != "void" )
	      str << "    " << javaType(result) << " result = " << defValue(result) << ";" << endl;

	    str << "    ByteArrayOutputStream data = new ByteArrayOutputStream();" << endl;
		
	    if ( !args.isEmpty() ) {
	      str << "    DataOutputStream os = new DataOutputStream(data);" << endl;
	      str << "    try" << endl;
	      str << "    {" << endl;

	      QStringList::Iterator itt, ita;
	      for (itt = argtypes.begin(), ita = args.begin(); itt != argtypes.end(); ++itt, ++ita)
		str << "      write_" << underscore(*itt) << "(os, " << *ita << ");" << endl;

	    }
	    
	    str << "    Response response = client().call(app(), obj(), \"" << funcName << "\", data.toByteArray(), false);" << endl;
	    str << "    if (response.returnValue)" << endl; 
	    str << "    {" << endl;
	    if ( result != "void" ) {
	      str << "      if (response.returnType.equals(\"" << result << "\"))" << endl;
	      str << "      {" << endl;
	      str << "        ByteArrayInputStream bi = new ByteArrayInputStream(response.returnData);" << endl;
	      str << "        DataInputStream is = new DataInputStream(bi);" << endl;
	      str << "        try" << endl;
	      str << "        {" << endl;
	      str << "          result = read_" << underscore(result) << "(is);" << endl;
	      str << "          setStatus( CallSucceeded );" << endl;
	      str << "        }" << endl;
	      str << "        catch (java.io.IOException e)" << endl;
	      str << "        {" << endl;
	      str << "          callFailed();" << endl;
	      str << "        }" << endl;
	      str << "      }" << endl;
	      str << "      else" << endl;
	      str << "        callFailed();" << endl;
	    } else {
	      str << "    setStatus(CallSucceeded);" << endl;
	    }
	    str << "    }" << endl;
	    str << "    else " << endl;
	    str << "      callFailed();" << endl;

	    
	    if (!args.isEmpty())
		{
		    str << "    }" << endl;
		    str << "    catch (java.io.IOException e)" << endl;
		    str << "    {" << endl;
		    str << "      callFailed();" << endl;
		    str << "    }" << endl;
		}

	    if ( result != "void" )
	      str << "    return result;" << endl;
	  }
	  str << "  }" << endl << endl;
	}
      }
      str << "}" << endl;
    }
  }
  impl.close();
}
