/*
 *   profilePropsPage.cpp
 *
 *   Copyright (C) 2004 Waldo Bastian <bastian@kde.org>
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License version 2 as
 *   published by the Free Software Foundation.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the Free Software
 *   Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

#include "profilePropsPage.h"

#include <qcombobox.h>
#include <qvalidator.h>

#include <kapplication.h>
#include <kconfig.h>
#include <klineedit.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kurlrequester.h>
#include <kuser.h>

#include "kioskrun.h"
#include "kiosksync.h"

static QStringList userList()
{
   KUser thisUser;
   QStringList result;
   result << thisUser.loginName();
   result << "root";

   KConfig *config = kapp->config();
   config->setGroup("General");
   result += config->readListEntry("PreviousUsers");
   result.sort();

   // Remove dupes
   QStringList::Iterator nextIt = result.begin();
   for(QStringList::Iterator it = result.begin();
       it != result.end(); it = nextIt)
   {
      nextIt = it;
      nextIt++;

      if ((nextIt != result.end()) && ((*it) == (*nextIt)))
         result.remove(it);
   }

   return result;
}


ProfilePropsPage::ProfilePropsPage(QWidget *parent, const QString &profile)
 : ProfilePropsPageUI(parent), PageWidget(this), m_profile(profile)
{
}

ProfilePropsPage::~ProfilePropsPage()
{
}

void ProfilePropsPage::slotProfileNameChanged()
{
  QString profile = editProfileName->text();
  if (m_fixedProfileDir)
  {
    QString profilePrefix = KioskRun::self()->getProfilePrefix();
    QString installDir = profilePrefix+profile+"/";
    labelInstallDir->setText(installDir);
  }
// TODO:  enableButtonOK(!profile.isEmpty());
}

void ProfilePropsPage::load()
{
  bool bNewProfile = false;
  if (m_profile.isEmpty())
  {
    m_profile = KioskRun::self()->newProfile();
    bNewProfile = true;
  }

  QString profilePrefix = KioskRun::self()->getProfilePrefix();
  m_fixedProfileDir = !profilePrefix.isEmpty();
  connect(editProfileName, SIGNAL(textChanged(const QString&)),
          this, SLOT(slotProfileNameChanged()));
  
#if 0
  connect(kurlInstallDir, SIGNAL(textChanged(const QString&)),
          this, SLOT(updateButtons()));
#endif

  comboUser->setEditable(true);
  comboUser->insertStringList(userList());

  QRegExp rx( "[^/ :]*" );
  QValidator* validator = new QRegExpValidator( rx, this );

  editProfileName->setValidator(validator);
  editProfileName->setFocus();

  QString description;
  QString installDir;
  QString installUser;

  KioskRun::self()->getProfileInfo(m_profile, description, installDir, installUser);

  if (!bNewProfile)
  {
     m_origProfile = m_profile;
     m_origInstallDir = installDir;
  }

  editProfileName->setText(m_profile);
  editDescription->setText(description);
  if (m_fixedProfileDir)
  {
    delete kurlInstallDir;
    labelInstallDir->setReadOnly(true);
    labelInstallDir->setText(installDir);
    setTabOrder(editDescription, comboUser);
    setTabOrder(comboUser, labelInstallDir);
  }
  else
  {
    delete labelInstallDir;
    kurlInstallDir->setMode(KFile::Directory);
    kurlInstallDir->setURL(installDir);
    setTabOrder(editDescription, comboUser);
    setTabOrder(comboUser, kurlInstallDir);
  }
  comboUser->setCurrentText(installUser);
}

bool ProfilePropsPage::save()
{
  QString user = comboUser->currentText();
  KUser userInfo(user);
  if (!userInfo.isValid())
  {
     KMessageBox::sorry(this,
       i18n("<qt>The user <b>%1</b> is not an existing user.</qt>").arg(user));
     comboUser->setFocus();
     return false;
  }
     
  m_profile = editProfileName->text();
  QString description = editDescription->text();
  QString installDir;
  if (m_fixedProfileDir)
  {
    installDir = labelInstallDir->text();
  }
  else
  {
    installDir = kurlInstallDir->url();
  }
  
  if (!installDir.endsWith("/"))
    installDir.append("/");

  if (!m_origInstallDir.isEmpty() && (installDir != m_origInstallDir))
  {
    KioskSync origInstallDir;
    origInstallDir.addDir(m_origInstallDir, KURL());
    QStringList fileList = origInstallDir.listFiles();
    fileList.remove(".kdeprofile");
    if (!fileList.isEmpty())
    {
       int msgResult = KMessageBox::warningContinueCancelList(this,
                          i18n("<qt>The directory for this profile has changed "
                               "from <b>%1</b> to <b>%2</b>.<p>"
                               "The following files under <b>%3</b> will be moved to <b>%4</b>")
                               .arg(m_origInstallDir, installDir, m_origInstallDir, installDir),
                          fileList,
                          i18n("Profile Directory Changed"));
       if (msgResult != KMessageBox::Continue)
          return false;
    }
    KioskRun::self()->setUser(user);
    if (!KioskRun::self()->move(m_origInstallDir, installDir, fileList))
       return false;
    if (QDir(m_origInstallDir).exists())
    {
       if (!KioskRun::self()->remove(m_origInstallDir))
          return false;
    }
  }

  QString installUser = user;

  bool result = KioskRun::self()->setProfileInfo( m_profile, description, installDir, installUser);

  if (result && !m_origProfile.isEmpty() && (m_origProfile != m_profile))
  {
     result = KioskRun::self()->deleteProfile( m_origProfile, false );
  }

  // Store this user for easy access later
  KConfig *config = kapp->config();
  config->setGroup("General");
  QStringList previousUsers= config->readListEntry("PreviousUsers");
  if (!previousUsers.contains(user))
  {
     previousUsers << user;
     config->writeEntry("PreviousUsers", previousUsers);
     config->sync();
  }

  return result;
}

void ProfilePropsPage::setFocus()
{
  editProfileName->setFocus();
}

QString ProfilePropsPage::subCaption()
{
  return QString::null;
}

#include "profilePropsPage.moc"
