#include "nokde_kprocess.h"

#if [[[TQT_VERSION IS DEPRECATED]]]<0x040000
#  include <tqprocess.h>
#  define Q3Process TQProcess
#else
#  include <TQt3Support/Q3Process>
#endif

#if defined(Q_OS_UNIX)
#  include <signal.h>
#endif

TDEProcess::TDEProcess(TQObject *parent, const char *name)
  : TQObject(parent, name)
{
  _process = new Q3Process(this);
  connect(_process, TQT_SIGNAL(processExited()), TQT_SLOT(processExitedSlot()));
  connect(_process, TQT_SIGNAL(readyReadStdout()), TQT_SLOT(readyReadStdoutSlot()));
  connect(_process, TQT_SIGNAL(readyReadStderr()), TQT_SLOT(readyReadStderrSlot()));
}

bool TDEProcess::start()
{
  _process->setArguments(_arguments);
  TQStringList env;
  if ( !_environment.isEmpty() ) {
    for (uint i=0; environ[i]; i++) env += environ[i];
    env += _environment;
  }
  return _process->start(env.isEmpty() ? 0 : &env);
}

void TDEProcess::processExitedSlot()
{
  readyReadStdoutSlot();
  readyReadStderrSlot();
  emit processExited(this);
}

void TDEProcess::readyReadStdoutSlot()
{
  TQByteArray a = _process->readStdout();
  emit receivedStdout(this, a.data(), a.count());
}

void TDEProcess::readyReadStderrSlot()
{
  TQByteArray a = _process->readStderr();
  emit receivedStderr(this, a.data(), a.count());
}

bool TDEProcess::writeStdin(const char *buffer, int len)
{
#if [[[TQT_VERSION IS DEPRECATED]]]<0x040000
  TQByteArray a;
  a.assign(buffer, len);
#else
  TQByteArray a(buffer, len);
#endif
  _process->writeToStdin(a);
  return true;
}

bool TDEProcess::kill()
{
  _process->kill();
  return true;
}

bool TDEProcess::kill(int n)
{
#if defined(Q_OS_UNIX)
  return ( ::kill(_process->processIdentifier(), n)!=-1 );
#elif defined(Q_OS_WIN)
  // #### impossible to do ??
  return false;
#endif
}

int TDEProcess::exitStatus() const
{
  return _process->exitStatus();
}

bool TDEProcess::isRunning() const
{
  return _process->isRunning();
}

void TDEProcess::setWorkingDirectory(const TQDir &dir)
{
  return _process->setWorkingDirectory(dir);
}

void TDEProcess::setUseShell(bool useShell)
{
  // ### TODO: just issue "/bin/sh" "-c" "command"
  Q_ASSERT(false);
}
