#define USE_POA

// Standard headers
#include <iostream>
#include <fstream>

// protocol headers
#include "corbaiface.h"
using namespace gsdlInterface;

#include "corbaconv_text_t.h"

// library headers
#include "fileutil.h"
//#include "gsdlhome.h"

// greenstone headers
#include "comtypes.h"
#include "recptproto.h"
#include "nullproto.h"

// local headers
#include "corbatext_t.h"

void corbatext_setToCorbaArray(text_tset set, corbatext_tset *cset);
void corbatext_corbaArrayToSet(corbatext_tset cset, text_tset *set);
void corbatext_mapToCorbaMap(text_tmap map, corbatext_tmap *tm);
void corbaresponse_resultDocInfoToCorba(ResultDocInfo_tarray docinfo, corbaResultDocInfo_array &corbainfo);

void corbaresponse_termInfoToCorba(TermInfo_tarray terminfo, corbaTermInfo_array &corbainfo) {
  TermInfo_tarray::iterator here = terminfo.begin();
  TermInfo_tarray::iterator end  = terminfo.end();
  unsigned int i;
	
  i = 0;

  while (here != end) 
    {
      corbainfo.length(i+1);
      
      corbainfo[i].frequency = here->freq;
      corbaconv_text_t::getCorbatext(here->term,corbainfo[i].term);
      corbatext_arrayToCorbaArray(here->matchTerms, &corbainfo[i].matchTerms);

      i ++;
      here ++;
    }
  std::cout << "Terminfo " << i << std::endl;
}

void corbatext_optionValueArrayToC(corbaOptionValue_array corba, OptionValue_tarray &array)
{
  unsigned int i = 0;
  OptionValue_t option;

  for (i = 0; i < corba.length(); i ++)
    {
      corbaconv_text_t::setCorbatext(option.name,corba[i].name);
      corbaconv_text_t::setCorbatext(option.value,corba[i].value);

      // std::cout << corbatext_string(corba[i].name) << "?" << option

      array.push_back(option);
    }
}

// corbaServer no longer inherits from corbaiface_skel since the change from using 
// BOA to POA in the Corba code upon updating Mico from version 2.3.5 to 2.3.13.
class corbaServer : virtual public POA_gsdlInterface::corbaiface
{
private:
  text_tarray collections;
  recptproto *protocol;
  text_t      gsdlhome;

  void openLogfile(text_t extension, ofstream &out)
  {
    char *cfilename;
    text_t filename;

    filename = filename_cat(gsdlhome, extension);
    cfilename = filename.getcstr();

    out.open(cfilename);
    delete cfilename;
  }

public:
  corbaServer(recptproto *protocol, text_t home)
  { 
    text_t dirname;
    char * cdirname;

    std::cout << "CorbaServer: gsdlhome = " << home << std::endl;

    this->gsdlhome = home;
    std::cout << gsdlhome.getcstr() << std::endl;
    dirname = filename_cat(gsdlhome, "/collect");
    cdirname = dirname.getcstr();
    if (!read_dir (cdirname, collections)) {
      std::cout << "Unable to read the gsdl directory; terminating" << std::endl;
      exit (1);
    }
    delete cdirname;

    std::cout << "Constructing set list server" << std::endl;
    this->protocol = protocol;

  }
  
  CORBA::Boolean initialise(corbaComError &err) 
  {
      ofstream      logout;
      int           reply;
      comerror_t    error = noError;

      this->openLogfile("/etc/corbaout.txt", logout);
      reply = protocol->init(error, logout);
      logout.close();
      return (reply != 0 ? 1 : 0);
    }

  void configure(const corbatext_t &corbaKey, const corbatext_tarray &corbaCfgline,corbaComError &err)
    {
      text_t        key;
      text_tarray   cfgline;
      comerror_t    error = noError;

      corbaconv_text_t::setCorbatext(key,corbaKey);
      corbatext_corbaArrayToArray(corbaCfgline, &cfgline);


      // ****
      std::cout << "Recieved " << key << " = ";
      for (int unsigned i=0; i<cfgline.size(); i++)
	{
	  std::cout << cfgline[i] << " ";
	}
      std::cout << std::endl;

      // DB // ****
      if (key=="gsdlhome")
	{  
	  text_tarray cfgline;
	  cfgline.push_back (gsdlhome);
	  std::cout << "Changing gsdlhome to " << gsdlhome << std::endl;
	  protocol->configure(key, cfgline, error);
	}
      else if (key=="httpdomain")
	{
	  // Only let gsdlhome through !!!! // ****
	  std::cout << "Supressing httpdomain" << std::endl;
	}
      else if (key=="httpprefix")
	{
	  std::cout << "Supressing httpprefix" << std::endl;
	}
      else
	{ 
	  protocol->configure(key, cfgline,error);
	}
    }

  void hasCollection(const corbatext_t &corbaCollect, CORBA::Boolean &has,
                     corbaComError &error) {
    // do nowt!
    corbaconv_text_t *cct;
    bool    _has;
    comerror_t err = noError;
    ofstream logout;

    this->openLogfile("/etc/corbaout.txt", logout);

    cct = new corbaconv_text_t(corbaCollect);

    std::cout << "Collection: " << cct->getcstr() << std::endl;

    protocol->has_collection(*cct, _has, err, logout); // 'cct' typecast to text_t
    if (_has)
      { 
	has = 1;
      }
    else
      {
	has = 0;
      }

    // std::cout << "  " << has << std::endl;

    delete cct;

    error = corbaNoError;
    logout.close();
  }

  void ping(const struct corbatext_t &corbaCollect, CORBA::Boolean &wasSuccess, corbaComError &corbaError)
  { 
    text_t collection;
    bool   success;
    comerror_t error = noError;
    ofstream logout;

    this->openLogfile("/etc/corbaout.txt", logout);

    corbaconv_text_t::setCorbatext(collection,corbaCollect);
    protocol->ping(collection, success, error, logout);

    corbaError = (corbaComError) error;
    wasSuccess = (CORBA::Boolean) success;
    logout.close();
  }

  void filter(const struct corbatext_t &corbaCollect,
	      const struct corbaFilterRequest &corbaRequest,
	      struct corbaFilterResponse &corbaResponse,
	      corbaComError &corbaError)
  {
    // variables for action
    FilterRequest_t request;
    FilterResponse_t response;
    comerror_t       error = noError;
    text_t           collection;
    ofstream         logout;

    this->openLogfile("/etc/corbaout.txt", logout);

    // copy collection id
    corbaconv_text_t::setCorbatext(collection,corbaCollect);

    // copy request values
    corbaconv_text_t::setCorbatext(request.filterName,corbaRequest.filter);
    corbatext_optionValueArrayToC(corbaRequest.filterOptions, request.filterOptions);
    corbatext_corbaArrayToArray(corbaRequest.docSet, &request.docSet);
    request.filterResultOptions = corbaRequest.filterResultOptions;
    corbaconv_text_t::setCorbatext(request.requestParams,corbaRequest.requestParams);
    corbaconv_text_t::setCorbatext(request.refParams,corbaRequest.refParams);
    corbatext_corbaArrayToSet(corbaRequest.fields, &request.fields);
    request.getParents = corbaRequest.getParents;

    protocol->filter(collection, request, response, error, logout);

    // copy response values
    corbaResponse.numDocs = response.numDocs;
    corbaResponse.isApprox = (::gsdlInterface::corbaIsApprox) response.isApprox;
    corbaresponse_termInfoToCorba(response.termInfo, corbaResponse.termInfo);
    corbaresponse_resultDocInfoToCorba(response.docInfo, corbaResponse.docInfo);

    // tidy up variables
    logout.close();
    corbaError = (corbaComError) error;
    std::cout << "Filter prepared" << corbaResponse.docInfo.length() << "," << corbaResponse.numDocs << std::endl;
  }

  void getCollectInfo(const struct corbatext_t &corbaCollect,
                      corbaColInfoResponse &corbaResponse,
                      corbaComError &corbaError)
  {
    ColInfoResponse_t response;
    comerror_t       error = noError;
    text_t           collection;
    ofstream logout;

    this->openLogfile("/etc/corbaout.txt", logout);

    corbaconv_text_t::setCorbatext(collection,corbaCollect);
    protocol->get_collectinfo(collection, response, error, logout);

    std::cout << "IsPublic  = " << ((response.isPublic)?"True":"False") << std::endl;
    std::cout << "IsBeta    = " << ((response.isBeta)  ?"True":"False") << std::endl;
    std::cout << "BuildDate = " << response.buildDate << std::endl;
    std::cout << "NumDocs   = " << response.numDocs << std::endl;
    std::cout << "NumBytes  = " << response.numBytes << std::endl;
    std::cout << "NumWords  = " << response.numWords << std::endl;
    std::cout << "UseBook   = " << ((response.useBook)  ?"True":"False") << std::endl;
    
    corbaResponse.useBook   = response.useBook;
    corbaResponse.isPublic  = response.isPublic;
    corbaResponse.isBeta    = response.isBeta;
    corbaResponse.buildDate = response.buildDate;
    corbatext_arrayToCorbaArray(response.languages, &corbaResponse.languages);
    corbatext_arrayToCorbaArray(response.ccsCols, &corbaResponse.ccsCols);
    corbaResponse.numDocs   = response.numDocs;
    corbaResponse.numBytes  = response.numBytes;
    corbaResponse.numWords  = response.numWords;

    corbatext_colmetamapToCorbaColmetamap(response.collectionmeta, &corbaResponse.collectionMeta);
    corbatext_mapToCorbaMap(response.format, &corbaResponse.format);
    corbatext_mapToCorbaMap(response.building, &corbaResponse.building);
    corbaconv_text_t::getCorbatext(response.httpdomain,corbaResponse.httpdomain);

    corbaconv_text_t::getCorbatext(response.httpprefix,corbaResponse.httpprefix);
    corbaconv_text_t::getCorbatext(response.receptionist,corbaResponse.receptionist);

    /* text_tmap::iterator f_here = response.format.begin();
    text_tmap::iterator f_end = response.format.end();
    while (f_here!=f_end)
    {
      std::cout << "**** format: " << f_here->first << " = " << f_here->second << std::endl;
      f_here++;
    } 
    */ // ****

    logout.close();
    corbaError = (corbaComError) error;
  }

  void getFilterOptions(const struct corbatext_t &corbaCollect,
			const struct corbatext_t &corbaFilterName,
			struct corbaFilterOptionsResponse &corbaResponse,
			enum corbaComError &corbaError)
  {   
    text_t collection;
    InfoFilterOptionsRequest_t request;
    InfoFilterOptionsResponse_t response;
    comerror_t error = noError;
    unsigned int i;
    ofstream logout;

    this->openLogfile("/etc/corbaout.txt", logout);

    corbaconv_text_t::setCorbatext(collection,corbaCollect);
    corbaconv_text_t::setCorbatext(request.filterName,corbaFilterName);
    protocol->get_filteroptions(collection, request, response, error, logout);

    // decode filters back into corba format
    FilterOption_tmap::iterator here = response.filterOptions.begin();
    FilterOption_tmap::iterator end = response.filterOptions.end();
    i = 0;
    while (here != end)
      {
	// set array for name/options to be one bigger
	corbaResponse.names.length(i+1);
	corbaResponse.options.length(i+1);

	// get left-hand side of map
	corbaconv_text_t::getCorbatext((*here).first,corbaResponse.names[i]);
	
	// get right-hand side of map
	corbaconv_text_t::getCorbatext((*here).second.name,corbaResponse.options[i].name);
	corbaResponse.options[i].type = 
	  (::gsdlInterface::corbaFilterType)(*here).second.type;
	corbaResponse.options[i].repeatable = 
	  (::gsdlInterface::corbaFilterRepeatable)(*here).second.repeatable;
	corbaconv_text_t::getCorbatext((*here).second.defaultValue,corbaResponse.options[i].defaultValue);
	corbatext_arrayToCorbaArray((*here).second.validValues, &corbaResponse.options[i].validValues);

	// take next iterators
	i++;
	here ++;
      }

    logout.close();
    corbaError = (corbaComError) error;
  }

  void getFilterInfo(const struct corbatext_t &corbaCollect, 
		     corbatext_tarray &filterNames, 
		     enum corbaComError &corbaError)
  { text_tarray ta;
    comerror_t error = noError;
    text_t collection;    
    InfoFiltersResponse_t response;
    ofstream logout;

    this->openLogfile("/etc/corbaout.txt", logout);

    corbaconv_text_t::setCorbatext(collection,corbaCollect);
    std::cout << collection.getcstr() << std::endl;
			    
    protocol->get_filterinfo(collection, response, error, logout);
    corbatext_setToCorbaArray(response.filterNames, &filterNames);

    corbaError = (corbaComError) error;
    logout.close();
  }
  
  void getDocument(const struct corbatext_t &corbaCollection, struct corbaDocRequest &corbaRequest, 
		   struct corbaDocResponse &corbaResponse,  enum corbaComError &corbaError)
  { DocumentRequest_t request;
    DocumentResponse_t response;
    comerror_t         error = noError;
    text_t             collection;
    ofstream logout;

    this->openLogfile("/etc/corbaout.txt", logout);

    // set up request
    corbaconv_text_t::setCorbatext(collection,corbaCollection);
    corbaconv_text_t::setCorbatext(request.OID,corbaRequest.OID);
    corbaconv_text_t::setCorbatext(request.docType,corbaRequest.docType);
    corbaconv_text_t::setCorbatext(request.docFormat,corbaRequest.docFormat);

    // do actual get document
    protocol->get_document(collection, request, response, error, logout);
    corbaconv_text_t::getCorbatext(response.doc,corbaResponse.doc);

    // decode response
    corbaError = (corbaComError) error;

    logout.close();
  }

  void getRssItems (const struct corbatext_t &corbaCollect,
		  const struct corbatext_t &corbaGsdlHome,
		  struct corbatext_t &corbaRssItems,
		  enum corbaComError &corbaError)
  {   
    text_t collection;
    text_t gsdlhome;
    text_t rss_items;
    comerror_t error = noError;
    ofstream logout;

    this->openLogfile("/etc/corbaout.txt", logout);

    corbaconv_text_t::setCorbatext(collection,corbaCollect);
    corbaconv_text_t::setCorbatext(gsdlhome,corbaGsdlHome);

    // do actual operation
    protocol->get_rss_items(collection, gsdlhome, rss_items, error, logout);
    corbaconv_text_t::getCorbatext(rss_items,corbaRssItems);
    
    // decode response
    corbaError = (corbaComError) error;

    logout.close();
  }

  void collectionList(corbatext_tarray &corbalist, corbaComError &error)
  {
    /* stringSeq *reply;
    unsigned int i;
    char *istring; */

    text_tarray collist;
    comerror_t  err;
    ofstream logout;

    std::cout << "Received collection list request" << std::endl;

    this->openLogfile("/etc/corbaout.txt", logout);

    protocol->get_collection_list(collist, err, logout);

    /*    reply = new stringSeq(collections.size());
    
    (*reply).length(collections.size());
    for (i = 0; i < collections.size(); i ++)
      {
	istring = collections[i].getcstr();
	(*reply)[i] = CORBA::string_dup(istring);
	delete istring;
      }
    
    return reply;
    */

    corbatext_arrayToCorbaArray(collist, &corbalist);
    std::cout << "Replying " << collist.size() << ": " << std::endl;

    for (int unsigned i = 0; i < collist.size(); i ++)
      {
	std::cout << collist[i];
	if (i<collist.size()-1) std::cout << ", ";
      }
    std::cout << std::endl;

    logout.close();
    // CORBA::string_dup(_listString);
  }
};

int main (int argc, char *argv[])
{
  nullproto protocol;
  collectset *cservers;
  text_t     gsdlhome;
  text_t     collecthome;

  cservers = new collectset(gsdlhome, collecthome);
  protocol.set_collectset(cservers);

  std::cout << "Started Corba ..." << std::endl;

  // ORB initialization
  // Initialize the ORB
  CORBA::ORB_var orb = CORBA::ORB_init( argc, argv, "mico-local-orb" );

#if defined(USE_POA)
  // Obtain a reference to the RootPOA and its Manager
  CORBA::Object_var poaobj = orb->resolve_initial_references ("RootPOA");
  PortableServer::POA_var poa = PortableServer::POA::_narrow (poaobj);
  PortableServer::POAManager_var mgr = poa->the_POAManager();
#else
  CORBA::BOA_var boa = orb->BOA_init( argc, argv, "mico-local-boa" );
#endif

  std::cout << "Initialised ORB and P/BOA" << std::endl;


  // Create the Server object (the object that inherits from the POA_gsdlInterface::corbaiface
  corbaServer* server = new corbaServer(&protocol, gsdlhome);

  // Activate the Servant (server)
#if defined(USE_POA)
  PortableServer::ObjectId_var oid = poa->activate_object (server);
#endif

  std::cout << "Initialised server" << std::endl;

  CORBA::Object_var ref = poa->id_to_reference ( oid.in() );
  CORBA::String_var str = orb->object_to_string( ref.in() );

  std::cout << "Mapped Corba object to string" << std::endl;

  // Write referene to file
  // write id to "naming service"
  ofstream out ("/tmp/localcorba.objid");
	if (out.is_open()) {
	  	out << str.in() << std::endl;
		if (out.fail() || out.bad()) {
			std::cout << "Failed " << std::endl;
		}
		out.close ();
	}
	else {
	  	std::cout << "Unable to write string" << str.in() << " to file /tmp/localcorba.objid" << std::endl;
		std::cout << "Please check the file permissions/ownership" << std::endl;
		return 0;
	}
	std::cout << "Corba string is " << str.in() << std::endl;

	// Activate the POA and start serving requests
  // indicate readiness and run
#if defined(USE_POA)
  mgr->activate ();
  //poa->the_POAManager()->activate();
#else
  boa->impl_is_ready( CORBA::ImplementationDef::_nil() );
#endif
  orb->run ();

#if defined(USE_POA)
  // Shutdown (never reached)
  poa->destroy (TRUE, TRUE);
  delete server; // should I include this????
#else
  CORBA::release( server );
#endif
  return 0;
}

