/***************************************************************************
                           commandengine.cpp  -  kfr commands feature class
                                      -------------------
    begin                : fri aug  13 15:29:46 CEST 2004

    copyright            : (C) 2004 Emiliano Gulmini
    email                : emi_barbarossa@yahoo.it
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

// QT
#include <tqdatetime.h>
#include <tqfile.h>
#include <tqtextstream.h>
#include <tqdom.h>

// KDE
#include <kuser.h>
#include <krandomsequence.h>
#include <kprocess.h>

// local
#include "commandengine.h"

TQString CommandEngine::datetime(const TQString& opt, const TQString& arg)
{
  Q_UNUSED(arg);
  if(opt == "iso")
    return TQDateTime::currentDateTime(TQt::LocalTime).toString(TQt::ISODate);
  if(opt == "local")
    return TQDateTime::currentDateTime(TQt::LocalTime).toString(TQt::LocalDate);
  return TQString();
}

TQString CommandEngine::user(const TQString& opt, const TQString& arg)
{
  Q_UNUSED(arg);
  KUser u;
  if(opt == "uid")
    return TQString::number(u.uid(),10);
  if(opt == "gid")
    return TQString::number(u.gid(),10);
  if(opt == "loginname")
    return u.loginName();
  if(opt == "fullname")
    return u.fullName();
  if(opt == "homedir")
    return u.homeDir();
  if(opt == "shell")
    return u.shell();
  return TQString();
}

TQString CommandEngine::loadfile(const TQString& opt, const TQString& arg)
{
  Q_UNUSED(arg);

  TQFile f(opt);
  if(!f.open(IO_ReadOnly)) return TQString();

  TQTextStream t(&f);

  TQString s = t.read();

  f.close();

  return s;
}

TQString CommandEngine::empty(const TQString& opt, const TQString& arg)
{
  Q_UNUSED(opt);
  Q_UNUSED(arg);
  return "";
}

TQString CommandEngine::mathexp(const TQString& opt, const TQString& arg)
{
  /* We will use bc 1.06 by Philip A. Nelson <philnelson@acm.org> */
  //Q_UNUSED(opt);
  Q_UNUSED(arg);

  TQString tempOpt = opt;
  tempOpt.replace("ln","l");
  tempOpt.replace("sin","s");
  tempOpt.replace("cos","c");
  tempOpt.replace("arctan","a");
  tempOpt.replace("exp","e");
  
  TQString program = "var=("+tempOpt+");print var";
  TQString script = "echo '"+program+"' | bc -l;";

  TDEProcess* proc = new TDEProcess();

  proc->setUseShell(true);

  *(proc) << script;

   connect(proc, TQ_SIGNAL(receivedStdout(TDEProcess*,char*,int)), this, TQ_SLOT(slotGetScriptOutput(TDEProcess*,char*,int)));
   connect(proc, TQ_SIGNAL(receivedStderr(TDEProcess*,char*,int)), this, TQ_SLOT(slotGetScriptError(TDEProcess*,char*,int)));
   connect(proc, TQ_SIGNAL(processExited(TDEProcess*)), this, TQ_SLOT(slotProcessExited(TDEProcess*)));

  //Through slotGetScriptOutput, m_processOutput contains the result of the TDEProcess call
   if(!proc->start(TDEProcess::Block, TDEProcess::All))
     {
       return TQString();
     }
   else
     {
       proc->wait();
     }
   if(proc)
     delete proc;

   TQString tempbuf = m_processOutput;
   m_processOutput = TQString();

   return tempbuf;

}

TQString CommandEngine::random(const TQString& opt, const TQString& arg)
{
  Q_UNUSED(arg);
  long seed;
  if(opt.isEmpty())
    {
      TQDateTime dt;
      seed = dt.toTime_t();
    }
  else
    seed = opt.toLong();

  KRandomSequence seq(seed);
  return TQString::number(seq.getLong(1000000),10);
}

TQString CommandEngine::stringmanip(const TQString& opt, const TQString& arg)
{
  Q_UNUSED(opt);
  Q_UNUSED(arg);
  return "";
}

TQString CommandEngine::variableValue(const TQString &variable)
{
  TQString s = variable;

  s.remove("[$").remove("$]").remove(" ");

  if(s.contains(":") == 0)
    return variable;
  else
    {
      TQString leftValue = s.section(":",0,0),
              midValue = s.section(":",1,1),
              rightValue = s.section(":",2,2);

      TQString opt = midValue;
      TQString arg = rightValue;

      if(leftValue == "stringmanip")
        return stringmanip(opt, arg);
      if(leftValue == "datetime")
        return datetime(opt, arg);
      if(leftValue == "user")
        return user(opt, arg);
      if(leftValue == "loadfile")
        return loadfile(opt, arg);
      if(leftValue == "empty")
        return empty(opt, arg);
      if(leftValue == "mathexp")
        return mathexp(opt, arg);
      if(leftValue == "random")
        return random(opt, arg);

      return variable;
    }
}

//SLOTS
void CommandEngine::slotGetScriptError(TDEProcess* proc, char* s, int i)
{
  Q_UNUSED(proc);
  Q_UNUSED(proc);
  TQCString temp(s,i+1);
  if(temp.isEmpty() || temp == "\n") return;
}

void CommandEngine::slotGetScriptOutput(TDEProcess* proc, char* s, int i)
{
  Q_UNUSED(proc);
  TQCString temp(s,i+1);

  if(temp.isEmpty() || temp == "\n") return;

  m_processOutput += TQString::fromLocal8Bit(temp);
}

void CommandEngine::slotProcessExited(TDEProcess* proc)
{
  Q_UNUSED(proc);
}

#include "commandengine.moc"
