/***************************************************************************
 *   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 <qstringlist.h>
#include <qregexp.h>

#include <klocale.h>
#include <kuser.h>
#include <kmessagebox.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(QString s, bool translate)
{
  prefix = "ML:";
  preUSER = "USER:";
  preCMD = "CMD:";
  mValue = s;

  transform();

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


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()
{
  QString cmd = QStringList::split(prefix + preCMD, mValue)[0];
  QStringList parts = QStringList::split(" ", cmd);

  KShellProcess *proc = new KShellProcess;

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

  connect(proc, SIGNAL(processExited(KProcess*)), this, SLOT(processExited(KProcess*)));
  connect(proc, SIGNAL(receivedStdout(KProcess*, char*, int)), this, SLOT(receivedStdout(KProcess*, char*, int)));

  mValue = "";

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


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


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

#include "magiclabel.moc"
