/////////////////////////////////////////////////////////////////////////////////
//      $Id: pkgOptions.cpp,v 1.13.4.1 2002/12/13 15:20:22 toivo Exp $
//
// File  : pkgOptions.cpp
// Author: Toivo Pedaste
//

#include "../config.h"
// qt headers
#include <qlabel.h>

#include <klocale.h>
#include <kglobal.h>
#include <kglobalsettings.h>
#include <klistview.h>
#include <kseparator.h>

#include "pkgOptions.h"
#include "managementWidget.h"
#include "debInterface.h"
#include "kpackage.h"

///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////

pkgOptions::pkgOptions(pkgInterface *pki, QWidget *parent)
  :  KDialog(parent,0,TRUE)
{
  //  setFrameStyle(QFrame::Raised | QFrame::Panel);

  pkgInt = pki;

  hide();

  notModified = TRUE;
  running = FALSE;
}

// Destructor
pkgOptions::~pkgOptions()
{
  //  int i;
  //  for (i = 0; i < bnumber; i++) {
  //    delete(Boxs[i]);
  //  }
}

// Set up the sub-widgets
void pkgOptions::setupWidgets(QPtrList<param> &pars)
{
  int i;

  // Create widgets
  title = new QLabel("", this);
  QFont f( KGlobalSettings::generalFont());
  f.setBold(true);
  f.setPointSize(f.pointSize()+6);
  title->setFont(f);
  //  title->setAutoResize(TRUE);
  //  title->update();

  installButton = new QPushButton(insType,this);
  cancelButton = new QPushButton(i18n("Cancel"),this);
  // count number of buttons
  bnumber = pars.count();

  Boxs = new QCheckBox *[bnumber];
  param *p;
  i = 0;
  for ( p=pars.first(); p != 0; p=pars.next(), i++ ) {
    Boxs[i] = new QCheckBox(p->name, this);
    Boxs[i]->setChecked(p->init);
  }

  // Connections
  connect(installButton,SIGNAL(clicked()),SLOT(pkginstallButtonClicked()));
  connect(cancelButton,SIGNAL(clicked()),SLOT(cancelButtonClicked()));

  // Do the layout
  vlayout = new QBoxLayout(this, QBoxLayout::TopToBottom, marginHint(), spacingHint());
  vlayout->addWidget(title,0);

  {
    hlayout = new QBoxLayout(vlayout,QBoxLayout::LeftToRight, spacingHint());

    {
      layout = new QBoxLayout(hlayout,QBoxLayout::TopToBottom, spacingHint());

      packages = new KListView(this);
      layout->addWidget(packages,20);
      packages->addColumn(i18n("PACKAGES"),200);

      connect(packages, SIGNAL(selectionChanged ( QListViewItem * )),
	    this, SLOT(slotSearch( QListViewItem * )));

      layout->addStretch(1);
      for (i = 0; i < bnumber; i++) {
	layout->addWidget(Boxs[i],1);
      }
      layout->addWidget(new KSeparator(KSeparator::HLine, this), 2);

      QBoxLayout *buttons = new QBoxLayout(QBoxLayout::LeftToRight);
      layout->addLayout(buttons);

      buttons->addWidget(installButton,2);
      buttons->addStretch(1);
      buttons->addWidget(cancelButton,2);
    }
    {
      term = new kpTerm(kpty,this);
      hlayout->addWidget(term);
    }
  }
  resize(minimumSize());
  //  hlayout->activate();
  //  layout->activate();
}

void pkgOptions::setup(packageInfo *p, QString type) {
  QPtrList<packageInfo> *pl = new QPtrList<packageInfo>;
  pl->append(p);
  setup(pl,type);
}

void pkgOptions::setup(QPtrList<packageInfo> *pl, QString)
{
 QString s;
 notModified = TRUE;

 packList = pl;

  packages->clear();
  packageInfo *p;

  QStringList plist, rlist, clist;
  QDict<QString> dict;
  QString mark("x");
  for ( p = pl->first(); p != 0; p = pl->next() ) {
    QString file =  p->getFilename();
    plist += p->getProperty("name");
    if (file.isEmpty()) {
      clist += p->getProperty("name");
    }
    dict.insert(p->getProperty("name"), &mark);
  }

  packageInfo *pk;
  if (clist.count() > 0) {
    rlist = pkgInt->listInstalls(clist, installer);
    for ( QStringList::Iterator it = rlist.begin(); it != rlist.end(); ++it ) {
      if (!dict[*it]) {
	plist.append(*it);
	QString dirIndex = *it + pkgInt->typeID;
	if (installer) {
	  pk = kpackage->management->dirUninstPackages->find(dirIndex);
	} else {
	  pk = kpackage->management->dirInstPackages->find(dirIndex);
	}
	if (pk) {
	  //	  kdDebug() << "FF=" << dirIndex << "\n";
	  pl->append(pk);
	} else {
	  //	  kdDebug() << "uF=" << dirIndex << "\n";
	}
      }
    }
  }

  //  title->setText(i18n("%1: 1 %2 Package", "%1: %n %2 Packages", plist.count())
  //                 .arg(insType).arg(pkgInt->name));
  // Doesn't compile for me

 if (plist.count() == 1) {
   s = i18n("%1: 1 %2 Package").arg(insType).arg(pkgInt->name);
 } else {
   s = i18n("%1: %2 %3 Packages").arg(insType).arg(plist.count()).arg(pkgInt->name);
 }
 title->setText(s);

  for (QStringList::Iterator pit = plist.begin(); pit != plist.end(); ++pit ) {
    kdDebug() << "P=" << *pit << "\n";
    new QListViewItem(packages, *pit);
  }
  cancelButton->setText(i18n("Cancel"));
}

// install button has been clicked....so install the package
void pkgOptions::pkginstallButtonClicked()
{
  int i;
  QStringList r;
  notModified = FALSE;

  // Collect data from check boxes
  int installFlags = 0;

  for (i = 0; i < bnumber; i++) {
    installFlags |= (Boxs[i]->isChecked()) << i;
  }

  test = FALSE;
  QString s = doPackages(installFlags, packList, test);
  // A "0=" or "1=" indicates it was actually (un)installed by the doPackages
  // routine instead of just returning a command to execute

  kdDebug() <<  "S=" << s << "\n";
  if (s == "0=") {
    cancelButtonClicked();
  } else if (s.left(2) == "1=") {
    term->textIn(s.mid(2));
  } else {
    connect(term,SIGNAL(result(QStringList &, int)),
	 this,SLOT(slotResult(QStringList &, int)));

    installButton->setEnabled(FALSE);

    if (term->run(s, r)) {
      running = TRUE;
      cancelButton->setText(i18n("Cancel"));
    } else {
      reset();
    }
  }
}

void pkgOptions::slotSearch(QListViewItem *item)
{
  QString s = item->text(0);
  kdDebug() << "searchI=" << s << "h=" << pkgInt->head <<"\n";

  packageInfo *p;
  for ( p = packList->first(); p != 0; p = packList->next() ) {
    if (s == p->getProperty("name")) {
      kpackage->management->doChangePackage(p);
      break;
    }
  }
}

void pkgOptions::reset() {
  installButton->setEnabled(TRUE);
  cancelButton->setText(i18n("Done"));
  disconnect(term,SIGNAL(result(QStringList &, int)),
	 this,SLOT(slotResult(QStringList &, int)));
  running = FALSE;
}

void pkgOptions::slotResult(QStringList &, int ret)
{
  reset();
  if (ret == 0 && !test) {
    term->done();
    accept();
  }
}

void pkgOptions::cancelButtonClicked()
{
  if (running) {
    term->cancel();
    reset();
  }
  term->done();
  if (notModified || test)
    reject();
  else
    accept();
}

///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
pkgOptionsI::pkgOptionsI(pkgInterface *pkg, QWidget *parent):
  pkgOptions(pkg, parent)
{
  insType = i18n("Install");
  installer = TRUE;
  setupWidgets(pkg->paramsInst);
}

QString pkgOptionsI::doPackages(int installFlags, QPtrList<packageInfo> *p, bool &test)
{
  return pkgInt->install(installFlags, p, test);
}

///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
pkgOptionsU::pkgOptionsU(pkgInterface *pkg, QWidget *parent):
  pkgOptions(pkg, parent)
{
  insType = i18n("Uninstall");
  installer = FALSE;
  setupWidgets(pkg->paramsUninst);
}

QString pkgOptionsU::doPackages(int installFlags, QPtrList<packageInfo> *p, bool &test)
{
  return pkgInt->uninstall(installFlags, p, test);
}
#include "pkgOptions.moc"
