/*****************************************************************
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 <tqdom.h>
#include <tqfile.h>
#include <tqtextstream.h>
#include <tqstring.h>
#include <tqregexp.h>

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


TQString javaType(TQString type)
{
    if (type == "bool")
	return "boolean";
    if (type == "TQString")
	return "String";
    if (type == "TQCString")
	return "String";
    if (type == "TQStringList")
	return "String[]"; 
    if (type == "short int")
	return "short";
    if (type == "long int")
	return "int";

    return type;
}


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

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


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

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


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

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


TQString underscore(TQString in)
{
  return in.replace(TQRegExp(" "), "_");
}


TQString defValue(TQString type)
{
  if (type == "bool")
    return "false";
  if (type == "TQString")
    return "null";
  if (type == "TQStringList")
    return "null";
  if (type == "DCOPRef")
      return "null";
  if (type == "TQCString")
      return "null";

  return "0";
}


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

  TQTextStream 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.trinitydesktop.DCOP.*;" << endl;
  str << endl << endl;

  TQDomElement e = de.firstChild().toElement();
  for( ; !e.isNull(); e = e.nextSibling().toElement() ) {
    if ( e.tagName() == "CLASS" ) {
      TQDomElement n = e.firstChild().toElement();
      ASSERT( n.tagName() == "NAME" );
      TQString className = n.firstChild().toText().data() + "_stub";
	
      // find dcop parent ( rightmost super class )
      TQString DCOPParent;
      TQDomElement 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" ) {
	  TQDomElement r = s.firstChild().toElement();
	  ASSERT( r.tagName() == "TYPE" );
	  TQString 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" );
	  TQString funcName = r.firstChild().toText().data();
	  str << funcName << "(";

	  TQStringList args;
	  TQStringList argtypes;
	  bool first = true;
	  r = r.nextSibling().toElement();
	  for( ; !r.isNull(); r = r.nextSibling().toElement() ) {
	    if ( !first )
	      str << ", ";
	    first = false;
	    ASSERT( r.tagName() == "ARG" );
	    TQDomElement 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(TQString("arg") + TQString::number(args.count())) ;
	    str << args.last();
	  }
	  str << ")";

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

	  funcName += "(";
	  first = true;
	  for( TQStringList::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;

	      TQStringList::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;

	      TQStringList::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();
}
