// fieldsel.C
//
// This program is free software. See the file COPYING for details.
// Author: Mattias Engdegård, 1997

//
// 2000-02-27 Espen Sand <espen@kde.org>
// Converted to KDialogBase
//

#include <qcheckbox.h>
#include <qlabel.h>
#include <qlayout.h>

#include <klocale.h>

#include "proc.h"
#include "fieldsel.h"

FieldSelect::FieldSelect( Procview *pv, Proc *proc, QWidget *parent, 
			  const char *name, bool modal ) 
  : KDialogBase( i18n("Select Fields"), Cancel, Cancel, Cancel, parent, name, 
		 modal, true, QString::null, QString::null, i18n("&Close") ),
  nbuttons(proc->cats.size()), disp_fields(nbuttons), procview(pv)
{
  QFrame *page = makeMainWidget();
  QVBoxLayout *topLayout = new QVBoxLayout( page, 0, 0 );

  updating = FALSE;
  buts = new QCheckBox*[nbuttons];

  QGridLayout *glay = new QGridLayout(topLayout, (nbuttons + 1) / 2, 5 );
  glay->addColSpacing(2, spacingHint()*2);
  glay->setColStretch(2, 10);

  int half = (nbuttons + 1) / 2;
  for(int i = 0; i < nbuttons; i++) 
  {
    QCheckBox *but = new QCheckBox(proc->cats[i]->name, page);
    QLabel *desc = new QLabel(proc->cats[i]->help, page);
    if(i < half) 
    {
      glay->addWidget(but, i, 0);
      glay->addWidget(desc, i, 1);
    } 
    else 
    {
      glay->addWidget(but, i-half, 3);
      glay->addWidget(desc, i-half, 4);
    }
    buts[i] = but;
    connect(but, SIGNAL(toggled(bool)), this, SLOT(field_toggled(bool)));
  }
  update_boxes();
}


// one of the fields was toggled (we don't know which one yet)
void FieldSelect::field_toggled(bool)
{
  if(updating) return;
  set_disp_fields();
  for(int i = 0; i < nbuttons; i++)
    if(buts[i]->isChecked() != disp_fields.testBit(i))
      if(buts[i]->isChecked())
	emit added_field(i);
      else
	emit removed_field(i);
}


void FieldSelect::set_disp_fields()
{
  disp_fields.fill(FALSE);
  int n = procview->cats.size();
  for(int i = 0; i < n; i++)
    disp_fields.setBit(procview->cats[i]->index);
}

void FieldSelect::update_boxes()
{
  set_disp_fields();
  updating = TRUE;
  for(int i = 0; i < nbuttons; i++)
    buts[i]->setChecked(disp_fields.testBit(i));
  updating = FALSE;
}


