#include <process.h>
#include "ClusterServer.hh"

#include "Syslog.h"

/*
 * class ClusterServer
 */
// structors:

ClusterServer::ClusterServer(ClusterIF::Name name)
  :m_driver(name) {}

ClusterServer::~ClusterServer() {
  while( !m_results.empty() ) {
    ClusterOutput *to_del = m_results.front();
    m_results.pop_front();
    delete to_del;
  }
}

// Manipulators :

ClusterOutput &ClusterServer::get(Symbol const &out) {
  if( !m_results.exists(out) ) {
#ifdef DEBUG
    Syslog::write("ClusterServer : creating acces to %s", out);
#endif 
    ClusterOutput *tmp = new ClusterOutput(out, SharedData::Read);
    m_results.add(out, tmp);
  }
  return *m_results.getRef(out);
}

ClusterIF::Status ClusterServer::getCluster(ClusterIF::Name cluster,
					    unsigned short *best,
					    double *distance) {
  try {
    ClusterOutput &out = get(cluster);
    out.read();
#if 0
    Syslog::write("ClusterServer: %s Data read <%d, %g>",
		  cluster,
		  out.data.bestCluster,
		  out.data.distance);
#endif // 0
    *best = (unsigned short)out.data.bestCluster;
    *distance = out.data.distance;
    return ClusterIF::Ok;
  } catch(...) {
    Syslog::write("ClusterServer:getCluster - caught an exception");
    return ClusterIF::FailedRead;
  }
}

int ClusterServer::spawnAuxTasks() {
  char *program = (char *)m_driver.c_str();

  char errorBuf[256];
  char buf[256];
 
  pid_t pid;
 
  switch ((pid = fork())) {
     
  case 0:
    // In child
    // Execute server program
    // execlp(program, program, "-serial", _serialParams->string(), 0);
    execlp(program, program, "", 0, 0);

    sprintf(errorBuf, 
	    "Task::spawnServer() - execlp() of \"%s\" failed", program);

    perror(errorBuf);
 
    break;

  case -1:
    perror("Task::spawnServer() - fork() failed");
    return -1;
  }

  return 0;
  
}
