/***************************************************************************
 *   Copyright (C) by                                                      *
 *     - 2005: Christian Leh <moodwrod@web.de>                             *
 *                                                                         *
 *   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.                                   *
 *                                                                         *
 ***************************************************************************/

#include <tqstringlist.h>
#include <tqregexp.h>

#include <tdelocale.h>
#include <kuser.h>
#include <tdemessagebox.h>

#include "magiclabel.h"

// This class is still very simple (as most of the classes)
// They get all improved later when "OpenGL Effect Widget" structure is completed

MagicLabel::MagicLabel(TQString s, bool translate)
{
  prefix = "ML:";
  preUSER = "USER:";
  preCMD = "CMD:";
  mValue = s;

  transform();

  if (translate)
    mValue = i18n(mValue.utf8());
}


void MagicLabel::transform()
{
  if (mValue.contains(prefix + preUSER))
    getUserInfo();
  else if (mValue.startsWith(prefix + preCMD))
    getCommandOutput();
}


void MagicLabel::getUserInfo()
{
  static KUser user;

  if (mValue.contains(prefix + preUSER + "loginname"))
    mValue = mValue.replace(prefix + preUSER + "loginname", user.loginName());
  else if (mValue.contains(prefix + preUSER + "fullname"))
    mValue = mValue.replace(prefix + preUSER + "fullname", user.fullName());
  else if (mValue.contains(prefix + preUSER + "homedir"))
    mValue = mValue.replace(prefix + preUSER + "homedir", user.homeDir());
}


void MagicLabel::getCommandOutput()
{
  TQString cmd = TQStringList::split(prefix + preCMD, mValue)[0];
  TQStringList parts = TQStringList::split(" ", cmd);

  KShellProcess *proc = new KShellProcess;

  for (int i = 0; i < parts.count(); i++)
    *proc << parts[i];

  connect(proc, TQ_SIGNAL(processExited(TDEProcess*)), this, TQ_SLOT(processExited(TDEProcess*)));
  connect(proc, TQ_SIGNAL(receivedStdout(TDEProcess*, char*, int)), this, TQ_SLOT(receivedStdout(TDEProcess*, char*, int)));

  mValue = "";

  if (!proc->start(TDEProcess::Block, TDEProcess::Stdout))
    KMessageBox::information(0, TQString("Could not start process: %1").arg(cmd));
}


void MagicLabel::receivedStdout(TDEProcess *proc, char *buffer, int buflen)
{
  TQString buf = TQString::fromLatin1(buffer, buflen);
  mValue += buf.replace("\n", "");
}


void MagicLabel::processExited(TDEProcess* proc)
{
  delete proc;
}

#include "magiclabel.moc"
