/*
 *   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 <tqcombobox.h>
#include <tqlabel.h>
#include <tqpushbutton.h>

#include <tdeapplication.h>
#include <tdeconfig.h>
#include <tdelistview.h>
#include <tdelocale.h>
#include <tdemessagebox.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(TQWidget* 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, TQ_SIGNAL(clicked()), this, TQ_SLOT(slotAddGroup()));
  connect(buttonDeleteGroup, TQ_SIGNAL(clicked()), this, TQ_SLOT(slotDeleteGroup()));
  connect(buttonAddUser, TQ_SIGNAL(clicked()), this, TQ_SLOT(slotAddUser()));
  connect(buttonDeleteUser, TQ_SIGNAL(clicked()), this, TQ_SLOT(slotDeleteUser()));

  connect(listGroups, TQ_SIGNAL(selectionChanged()), this, TQ_SLOT(slotUpdateButtons()));
  connect(listUsers, TQ_SIGNAL(selectionChanged()), this, TQ_SLOT(slotUpdateButtons()));
  
//  init();
  static bool firstTime = true;
  
  if (firstTime)
  {
     firstTime = false;
     TQTimer::singleShot(0, this, TQ_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 $TDEDIRS environment variable from the <b>starttde</b> "
              "script by adding the following line:<br><br>"
              "<i>export TDEDIRS=$(kiosktool-tdedirs)</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;
   TQStringList groupOrder;
   
   KioskRun::self()->getUserProfileMappings(groups, users, groupOrder);
   
   for ( TQStringList::ConstIterator it = groupOrder.begin();
         it != groupOrder.end(); ++it )
   {
      TQString group = *it;
      TQString profile = groups[group].join(",");
      new TQListViewItem(listGroups, group, profile);
   }

   for ( KioskRun::ProfileMapping::Iterator it = users.begin();
         it != users.end(); ++it )
   {
      TQString user = it.key();
      TQString profile = it.data().join(",");
      new TQListViewItem(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;
   TQStringList groupOrder;
   
   TQListViewItem *item = listGroups->firstChild();
   for(; item; item = item->nextSibling())
   {
      TQString group = item->text(0);
      TQStringList profiles = TQStringList::split(",", item->text(1));
      groups.insert(group, profiles);
      groupOrder.prepend(group);
   }

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

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

   m_allGroups.clear();
   setgrent();
   for (struct group *grp; (grp = getgrent()); )
   {
       TQString group = TQString::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)
   {
      TQString group = wid->comboGroup->currentText();
      TQString profile = wid->comboProfile->currentText();
      
      // Check for dupes
      TQListViewItem *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 TQListViewItem(listGroups, group, profile);
      listGroups->setSelected(item, true);
      slotUpdateButtons();
      return;
   }
}

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

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

void UserManagementPage::slotAddUser()
{
   TDEConfig *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(TQString::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)
   {
      TQString user = wid->comboUser->currentText();
      TQString profile = wid->comboProfile->currentText();

      // Check for dupes
      TQListViewItem *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 TQListViewItem(listUsers, user, profile);
      listUsers->setSelected(item, true);
      slotUpdateButtons();
      return;
   }
}

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

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

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

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

#include "userManagement.moc"
