/*
 *   userManagement.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 "userManagement.h"

#include <unistd.h>
#include <grp.h>
#include <pwd.h>
#include <sys/types.h>

#include <qcombobox.h>
#include <qlabel.h>
#include <qpushbutton.h>

#include <kapplication.h>
#include <kconfig.h>
#include <klistview.h>
#include <klocale.h>
#include <kmessagebox.h>

#include "kioskrun.h"

#include "userManagement_ui.h"
#include "userManagementGroup_ui.h"
#include "userManagementUser_ui.h"

#define AVAILABLE_SINCE "KDE 3.2.3"

UserManagementPage::UserManagementPage(QWidget* parent, const char* name, WFlags fl)
 : UserManagementUI(parent, name, fl), PageWidget(this)
{
  setCaption(i18n("Assign Profiles"));
  listGroups->setSorting(-1); // Disable sorting
  listGroups->setDragEnabled(true);
  listGroups->setAcceptDrops(true);
  
//  actionButton(KDialogBase::Ok)->setFocus();
  
  connect(buttonAddGroup, SIGNAL(clicked()), this, SLOT(slotAddGroup()));
  connect(buttonDeleteGroup, SIGNAL(clicked()), this, SLOT(slotDeleteGroup()));
  connect(buttonAddUser, SIGNAL(clicked()), this, SLOT(slotAddUser()));
  connect(buttonDeleteUser, SIGNAL(clicked()), this, SLOT(slotDeleteUser()));

  connect(listGroups, SIGNAL(selectionChanged()), this, SLOT(slotUpdateButtons()));
  connect(listUsers, SIGNAL(selectionChanged()), this, SLOT(slotUpdateButtons()));
  
//  init();
  static bool firstTime = true;
  
  if (firstTime)
  {
     firstTime = false;
     QTimer::singleShot(0, this, SLOT(slotShowNotice()));
  }
}

UserManagementPage::~UserManagementPage()
{
}

void UserManagementPage::slotShowNotice()
{
  KMessageBox::information(this, 
         i18n("<qt>The profiles that you define here are automatically applied when the "
              "user logs in to %1 or newer.<p>"
              "If you want to use these profiles in combination with older versions you need "
              "to manually set the $KDEDIRS environment variable from the <b>startkde</b> "
              "script by adding the following line:<br><br>"
              "<i>export KDEDIRS=$(kiosktool-kdedirs)</i><br><br>").arg(AVAILABLE_SINCE),
         i18n("Attention"), "user-profiles");
}

void UserManagementPage::load()
{
   listGroups->clear();
   listUsers->clear();

   m_allProfiles = KioskRun::self()->allProfiles();
   m_allProfiles.sort();

   KioskRun::ProfileMapping groups;
   KioskRun::ProfileMapping users;
   QStringList groupOrder;
   
   KioskRun::self()->getUserProfileMappings(groups, users, groupOrder);
   
   for ( QStringList::ConstIterator it = groupOrder.begin();
         it != groupOrder.end(); ++it )
   {
      QString group = *it;
      QString profile = groups[group].join(",");
      new QListViewItem(listGroups, group, profile);
   }

   for ( KioskRun::ProfileMapping::Iterator it = users.begin();
         it != users.end(); ++it )
   {
      QString user = it.key();
      QString profile = it.data().join(",");
      new QListViewItem(listUsers, user, profile);
   }
   slotUpdateButtons();
}

void UserManagementPage::slotUpdateButtons()
{
   buttonDeleteGroup->setEnabled(listGroups->selectedItem() != 0);
   buttonDeleteUser->setEnabled(listUsers->selectedItem() != 0);
}

bool UserManagementPage::save()
{
   KioskRun::ProfileMapping groups;
   KioskRun::ProfileMapping users;
   QStringList groupOrder;
   
   QListViewItem *item = listGroups->firstChild();
   for(; item; item = item->nextSibling())
   {
      QString group = item->text(0);
      QStringList profiles = QStringList::split(",", item->text(1));
      groups.insert(group, profiles);
      groupOrder.prepend(group);
   }

   item = listUsers->firstChild();
   for(; item; item = item->nextSibling())
   {
      QString user = item->text(0);
      QStringList profiles = QStringList::split(",", item->text(1));
      users.insert(user, profiles);
   }
   
   return KioskRun::self()->setUserProfileMappings(groups, users, groupOrder);
}

void UserManagementPage::slotAddGroup()
{
   KConfig *config = kapp->config();
   config->setGroup("General");
   QStringList groupBlacklist = config->readListEntry("GroupBlacklist");

   m_allGroups.clear();
   setgrent();
   for (struct group *grp; (grp = getgrent()); )
   {
       QString group = QString::fromUtf8(grp->gr_name);
       if (!groupBlacklist.contains(group))
           m_allGroups.append(group);
   }
   endgrent();
   m_allGroups.sort();

   KDialogBase dlg(this, "addGroup", true, i18n("Add Group Policy"),
      KDialogBase::Ok|KDialogBase::Cancel, KDialogBase::Ok, true );
      
   UserManagementGroupUI *wid = new UserManagementGroupUI(&dlg);
   wid->labelCaption->setFixedSize(wid->labelCaption->sizeHint());
   wid->comboGroup->insertStringList(m_allGroups);
   wid->comboProfile->insertStringList(m_allProfiles);
   wid->setFixedSize(wid->sizeHint());
   dlg.setMainWidget(wid);
   dlg.setFixedSize(dlg.sizeHint());
   while (dlg.exec() == KDialogBase::Accepted)
   {
      QString group = wid->comboGroup->currentText();
      QString profile = wid->comboProfile->currentText();
      
      // Check for dupes
      QListViewItem *item = listGroups->firstChild();
      for( ;item; item = item->nextSibling())
      {
         if (item->text(0) == group)
            break;
      }
      if (item)
      {
         int result = KMessageBox::warningContinueCancel(this,
                   i18n("<qt>You already have a profile defined for group <b>%1</b>. "
                        "Do you want to replace it?</qt>").arg(group), 
                   i18n("Duplicate Warning"),
                   i18n("&Replace"));
         if (result != KMessageBox::Continue)
            continue; // Go back to edit dialog
         delete item;
      }
      
      item = new QListViewItem(listGroups, group, profile);
      listGroups->setSelected(item, true);
      slotUpdateButtons();
      return;
   }
}

void UserManagementPage::slotDeleteGroup()
{
   QListViewItem *item = listGroups->selectedItem();
   if (!item)
      return;
      
   delete item;

   item = listGroups->currentItem();
   if (item)
      listGroups->setSelected(item, true);
   slotUpdateButtons();
}

void UserManagementPage::slotAddUser()
{
   KConfig *config = kapp->config();
   config->setGroup("General");
   int minUID = config->readNumEntry("FirstUIDShown", 500);

   m_allUsers.clear();
   setpwent();
   for (struct passwd *user; (user = getpwent()); )
   {
       if ((user->pw_uid >= (uid_t) minUID) || (user->pw_uid == 0))
           m_allUsers.append(QString::fromUtf8(user->pw_name));
   }
   endpwent();
   m_allUsers.sort();

   KDialogBase dlg(this, "addUser", true, i18n("Add User Policy"),
      KDialogBase::Ok|KDialogBase::Cancel, KDialogBase::Ok, true );
      
   UserManagementUserUI *wid = new UserManagementUserUI(&dlg);
   wid->labelCaption->setFixedSize(wid->labelCaption->sizeHint());
   wid->comboUser->insertStringList(m_allUsers);
   wid->comboProfile->insertStringList(m_allProfiles);
   wid->setFixedSize(wid->sizeHint());
   dlg.setMainWidget(wid);
   dlg.setFixedSize(dlg.sizeHint());
   while (dlg.exec() == KDialogBase::Accepted)
   {
      QString user = wid->comboUser->currentText();
      QString profile = wid->comboProfile->currentText();

      // Check for dupes
      QListViewItem *item = listUsers->firstChild();
      for( ;item; item = item->nextSibling())
      {
         if (item->text(0) == user)
            break;
      }
      if (item)
      {
         int result = KMessageBox::warningContinueCancel(this,
                   i18n("<qt>You already have a profile defined for user <b>%1</b>. "
                        "Do you want to replace it?</<qt>").arg(user), 
                   i18n("Duplicate Warning"),
                   i18n("&Replace"));
         if (result != KMessageBox::Continue)
            continue; // Go back to edit dialog
         delete item;
      }

      item = new QListViewItem(listUsers, user, profile);
      listUsers->setSelected(item, true);
      slotUpdateButtons();
      return;
   }
}

void UserManagementPage::slotDeleteUser()
{
   QListViewItem *item = listUsers->selectedItem();
   if (!item)
      return;
      
   delete item;

   item = listUsers->currentItem();
   if (item)
      listUsers->setSelected(item, true);
   slotUpdateButtons();
}

void UserManagementPage::setFocus()
{
   // TODO
}

QString UserManagementPage::subCaption()
{
   return i18n("Assign Profiles");
}

#include "userManagement.moc"
