/***************************************************************************
 *   Copyright (C) 2005-2006 by Niklas Knutsson                            *
 *   nq@altern.org                                                         *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   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 "qalculateeditdatasetdialog.h"
#include "qalculate_tde_utils.h"
#include "qalculateeditnamesdialog.h"

#include <string>
#include <tqgrid.h>
#include <klineedit.h>
#include <kpushbutton.h>
#include <kcombobox.h>
#include <tqlabel.h>
#include <tdelocale.h>
#include <tqvbox.h>
#include <tqhbox.h>
#include <tqcheckbox.h>
#include <tdemessagebox.h>
#include <tqlayout.h>
#include <ktextedit.h>
#include <tdelistview.h>
#include <ktabwidget.h>
#include <tqapplication.h>
#include <kstdguiitem.h>

extern PrintOptions printops;
extern tree_struct function_cats;

QalculateEditDataSetDialog::QalculateEditDataSetDialog(TQWidget *parent, const char *name) : KDialogBase(parent, name, true, i18n("Edit Data Set"), Ok | Cancel, Ok, false) {

	names_edit_dialog = NULL;
	edited_dataset = NULL;
	property_edit_dialog = NULL;

	tabs = new KTabWidget(this);
	setMainWidget(tabs);
	TQWidget *page1 = new TQWidget(this);
	TQWidget *page2 = new TQWidget(this);
	TQWidget *page3 = new TQWidget(this);
	tabs->addTab(page1, i18n("General"));
	tabs->addTab(page2, i18n("Properties"));
	tabs->addTab(page3, i18n("Function"));

	TQGridLayout *grid = new TQGridLayout(page1, 1, 1, spacingHint());
	grid->addWidget(new TQLabel(i18n("Title:"), page1), 0, 0);
	titleEdit = new KLineEdit(page1);
	grid->addWidget(titleEdit, 0, 1);
	grid->addWidget(new TQLabel(i18n("Data file:"), page1), 1, 0);
	fileEdit = new KLineEdit(page1);
	grid->addWidget(fileEdit, 1, 1);
	grid->addWidget(new TQLabel(i18n("Description:"), page1), 2, 0);
	descriptionEdit = new KTextEdit(page1);
	descriptionEdit->setTextFormat(TQTextEdit::PlainText);
	grid->addMultiCellWidget(descriptionEdit, 3, 3, 0, 1);
	grid->addWidget(new TQLabel(i18n("Copyright:"), page1), 4, 0);
	copyrightEdit = new KTextEdit(page1);
	copyrightEdit->setTextFormat(TQTextEdit::PlainText);
	grid->addMultiCellWidget(copyrightEdit, 5, 5, 0, 1);

	TQVBoxLayout *vbox = new TQVBoxLayout(page2, spacingHint());
	vbox->addWidget(new TQLabel(i18n("Properties:"), page2));
	propertiesView = new TDEListView(page2);
	propertiesView->addColumn(i18n("Title"));
	propertiesView->addColumn(i18n("Name"));
	propertiesView->addColumn(i18n("Type"));
	propertiesView->setSorting(-1);
	propertiesView->setRootIsDecorated(false);
	vbox->addWidget(propertiesView);
	TQHBoxLayout *hbox = new TQHBoxLayout(vbox, spacingHint());
	hbox->addItem(new TQSpacerItem(0, 0, TQSizePolicy::Expanding, TQSizePolicy::Minimum));
	newPropertyButton = new TQPushButton(i18n("New"), page2);
	hbox->addWidget(newPropertyButton);
	editPropertyButton = new TQPushButton(i18n("Edit"), page2);
	hbox->addWidget(editPropertyButton);
	deletePropertyButton = new TQPushButton(i18n("Delete"), page2);
	hbox->addWidget(deletePropertyButton);

	grid = new TQGridLayout(page3, 1, 1, spacingHint());
	grid->addWidget(new TQLabel(i18n("Name:"), page3), 0, 0);
	nameEdit = new KLineEdit(page3);
	grid->addWidget(nameEdit, 0, 1);
	hbox = new TQHBoxLayout(0, 0, spacingHint());
	grid->addMultiCellLayout(hbox, 1, 1, 0, 1);
	namesLabel = new TQLabel(page3);
	namesLabel->setAlignment(TQt::AlignRight);
	namesLabel->setSizePolicy(TQSizePolicy::Expanding, TQSizePolicy::Preferred);
	hbox->addWidget(namesLabel);
	namesButton = new TQPushButton(i18n("Names Details"), page3);
	hbox->addWidget(namesButton);
	grid->addWidget(new TQLabel(i18n("Object argument name:"), page3), 2, 0);
	objectArgumentEdit = new KLineEdit(page3);
	grid->addWidget(objectArgumentEdit, 2, 1);
	grid->addWidget(new TQLabel(i18n("Property argument name:"), page3), 3, 0);
	propertyArgumentEdit = new KLineEdit(page3);
	grid->addWidget(propertyArgumentEdit, 3, 1);
	grid->addWidget(new TQLabel(i18n("Default property:"), page3), 4, 0);
	defaultPropertyEdit = new KLineEdit(page3);
	grid->addWidget(defaultPropertyEdit, 4, 1);
	grid->addItem(new TQSpacerItem(5, 0, TQSizePolicy::Minimum, TQSizePolicy::Expanding));


	connect(namesButton, TQ_SIGNAL(clicked()), this, TQ_SLOT(editNames()));
	connect(nameEdit, TQ_SIGNAL(textChanged(const TQString&)), this, TQ_SLOT(nameChanged(const TQString&)));
	connect(newPropertyButton, TQ_SIGNAL(clicked()), this, TQ_SLOT(newProperty()));
	connect(editPropertyButton, TQ_SIGNAL(clicked()), this, TQ_SLOT(editProperty()));
	connect(deletePropertyButton, TQ_SIGNAL(clicked()), this, TQ_SLOT(deleteProperty()));
	connect(propertiesView, TQ_SIGNAL(selectionChanged()), this, TQ_SLOT(propertySelectionChanged()));
	
}

QalculateEditDataSetDialog::~QalculateEditDataSetDialog() {}


void QalculateEditDataSetDialog::propertySelectionChanged() {
	TQListViewItem *i = propertiesView->selectedItem();
	if(i) {
		editPropertyButton->setEnabled(propertiesItems[i]->isUserModified());
		deletePropertyButton->setEnabled(propertiesItems[i]->isUserModified());
	} else {
		editPropertyButton->setEnabled(false);
		deletePropertyButton->setEnabled(false);
	}
}

void QalculateEditDataSetDialog::updateDatasetPropertyList() {
	propertiesView->clear();
	propertiesItems.clear();
	editPropertyButton->setEnabled(false);
	deletePropertyButton->setEnabled(false);
	TQString str;
	TQListViewItem *i_prev = NULL;
	for(size_t i = 0; i < tmp_props.size(); i++) {
		if(tmp_props[i]) {
			str = "";
			switch(tmp_props[i]->propertyType()) {
				case PROPERTY_STRING: {
					str += i18n("text");
					break;
				}
				case PROPERTY_NUMBER: {
					if(tmp_props[i]->isApproximate()) {
						str += i18n("approximate");
						str += " ";
					}
					str += i18n("number");
					break;
				}
				case PROPERTY_EXPRESSION: {
					if(tmp_props[i]->isApproximate()) {
						str += i18n("approximate");
						str += " ";
					}
					str += i18n("expression");
					break;
				}
			}
			if(tmp_props[i]->isKey()) {
				str += " (";
				str += i18n("key");
				str += ")";
			}
			TQListViewItem *item = new TDEListViewItem(propertiesView, i_prev, tmp_props[i]->title(false).c_str(), tmp_props[i]->getName().c_str(), str);
			i_prev = item;
			propertiesItems[item] = tmp_props[i];
		}
	}
}

void QalculateEditDataSetDialog::slotOk() {

	std::string str = nameEdit->text().ascii();
	remove_blank_ends(str);
	if(str.empty() && (!names_edit_dialog || names_edit_dialog->isEmpty())) {
		//no name -- open dialog again
		tabs->setCurrentPage(2);
		nameEdit->setFocus();
		KMessageBox::error(this, i18n("Empty name field"));
		return;
	}
	//function with the same name exists -- overwrite or open dialog again
	if((!edited_dataset || !edited_dataset->hasName(str)) && (!names_edit_dialog || names_edit_dialog->isEmpty()) && CALCULATOR->functionNameTaken(str, edited_dataset) && KMessageBox::questionYesNo(this, i18n("A function with the same name already exists.\nDo you want to overwrite it?")) == KMessageBox::No) {
		tabs->setCurrentPage(2);
		nameEdit->setFocus();
		return;
	}
	
	DataSet *ds = edited_dataset;
	bool add_func = false;
	if(ds) {
		//edited an existing function
		ds->setTitle(titleEdit->text().ascii());
		ds->setDescription(descriptionEdit->text().ascii());
		if(ds->isLocal()) ds->setDefaultDataFile(fileEdit->text().ascii());
	} else {
		//new function
		ds = new DataSet(i18n("Data Sets").ascii(), "", fileEdit->text().ascii(), titleEdit->text().ascii(), descriptionEdit->text().ascii(), true);
		add_func = true;
	}
	TQString str2 = objectArgumentEdit->text().stripWhiteSpace();
	if(str2.isEmpty()) str2 = i18n("Object");
	Argument *arg = ds->getArgumentDefinition(1);
	if(arg) {
		arg->setName(str2.ascii());
	}
	str2 = propertyArgumentEdit->text().stripWhiteSpace();
	if(str2.isEmpty()) str2 = i18n("Property");
	arg = ds->getArgumentDefinition(2);
	if(arg) {
		arg->setName(str2.ascii());
	}
	ds->setDefaultProperty(defaultPropertyEdit->text().ascii());
	ds->setCopyright(copyrightEdit->text().ascii());
	DataPropertyIter it;
	for(size_t i = 0; i < tmp_props.size();) {
		if(!tmp_props[i]) {
			if(tmp_props_orig[i]) ds->delProperty(tmp_props_orig[i]);
			i++;
		} else if(tmp_props[i]->isUserModified()) {
			if(tmp_props_orig[i]) {
				tmp_props_orig[i]->set(*tmp_props[i]);
				i++;
			} else {
				ds->addProperty(tmp_props[i]);
				tmp_props.erase(tmp_props.begin() + i);
			}
		} else {
			i++;
		}
	}

	if(names_edit_dialog) {
		names_edit_dialog->saveNames(ds, str.c_str());
	} else {
		if(ds->countNames() == 0) {
			ExpressionName ename(str);
			ename.reference = true;
			ds->setName(ename, 1);
		} else {
			ds->setName(str, 1);
		}
	}
	if(add_func) {
		CALCULATOR->addDataSet(ds);
		ds->loadObjects();
		ds->setObjectsLoaded(true);
	}
		
	for(size_t i = 0; i < tmp_props.size(); i++) {
		if(tmp_props[i]) delete tmp_props[i];
	}
	tmp_props.clear();
	tmp_props_orig.clear();
	edited_dataset = ds;
	
	accept();

}

DataSet *QalculateEditDataSetDialog::editDataSet(DataSet *ds) {

	titleEdit->setFocus();

	tabs->setCurrentPage(0);
	if(names_edit_dialog) {
		delete names_edit_dialog;
		names_edit_dialog = NULL;
	}
	edited_dataset = ds;
	if(ds) {
		if(ds->isLocal())
			setCaption(i18n("Edit Data Set"));
		else
			setCaption(i18n("Edit Data Set (global)"));
	} else {
		setCaption(i18n("New Data Set"));
	}

	//clear entries
	fileEdit->setReadOnly(ds && !ds->isLocal());
	copyrightEdit->setReadOnly(ds && !ds->isLocal());
	nameEdit->clear();
	titleEdit->clear();
	fileEdit->clear();
	objectArgumentEdit->clear();
	propertyArgumentEdit->clear();
	defaultPropertyEdit->setText(i18n("info"));
	namesLabel->clear();
	descriptionEdit->clear();
	copyrightEdit->clear();
	nameEdit->setReadOnly(false);
	actionButton(Ok)->setEnabled(true);
	newPropertyButton->setEnabled(true);
	editPropertyButton->setEnabled(false);
	deletePropertyButton->setEnabled(false);
	if(ds) {
		//fill in original paramaters
		set_name_label_and_entry(ds, nameEdit, namesLabel);
		fileEdit->setText(ds->defaultDataFile().c_str());
		defaultPropertyEdit->setText(ds->defaultProperty().c_str());
		titleEdit->setText(ds->title(false).c_str());
		Argument *arg = ds->getArgumentDefinition(1);
		if(arg) {
			objectArgumentEdit->setText(arg->name().c_str());
		}
		arg = ds->getArgumentDefinition(2);
		if(arg) {
			propertyArgumentEdit->setText(arg->name().c_str());
		}
		descriptionEdit->setText(ds->description().c_str());
		copyrightEdit->setText(ds->copyright().c_str());
		DataPropertyIter it;
		DataProperty *dp = ds->getFirstProperty(&it);
		while(dp) {
			tmp_props.push_back(new DataProperty(*dp));
			tmp_props_orig.push_back(dp);
			dp = ds->getNextProperty(&it);
		}
	}
	updateDatasetPropertyList();

	if(exec() == TQDialog::Accepted) {
		ds = edited_dataset;
		edited_dataset = NULL;
		return ds;
	}
	edited_dataset = NULL;
	for(size_t i = 0; i < tmp_props.size(); i++) {
		if(tmp_props[i]) delete tmp_props[i];
	}
	tmp_props.clear();
	tmp_props_orig.clear();
	return NULL;
}

void QalculateEditDataSetDialog::editNames() {
	if(!names_edit_dialog) {
		names_edit_dialog = new QalculateEditNamesDialog(TYPE_FUNCTION, this);
		names_edit_dialog->setNames(edited_dataset, nameEdit->text(), false);
	} else {
		names_edit_dialog->setNames(edited_dataset, nameEdit->text(), true);
	}
	names_edit_dialog->exec();
	names_edit_dialog->setNamesLE(nameEdit, namesLabel);
}
void QalculateEditDataSetDialog::newProperty() {
	if(!property_edit_dialog) {
		property_edit_dialog = new QalculateEditDataPropertyDialog(this);
	}
	DataProperty *dp = new DataProperty(edited_dataset);
	dp->setUserModified(true);
	if(property_edit_dialog->editDataProperty(dp, true)) {
		tmp_props.push_back(dp);
		tmp_props_orig.push_back(NULL);
		updateDatasetPropertyList();
	} else {
		delete dp;
	}
}

void QalculateEditDataSetDialog::editProperty() {
	TQListViewItem *i = propertiesView->selectedItem();
	if(i == NULL) return;
	if(!property_edit_dialog) {
		property_edit_dialog = new QalculateEditDataPropertyDialog(this);
	}
	if(property_edit_dialog->editDataProperty(propertiesItems[i])) {
		updateDatasetPropertyList();
	}
}
void QalculateEditDataSetDialog::deleteProperty() {
	TQListViewItem *i = propertiesView->selectedItem();
	if(i == NULL) return;
	if(propertiesItems[i]->isUserModified()) {
		for(size_t index = 0; index < tmp_props.size(); index++) {
			if(tmp_props[index] == propertiesItems[i]) {
				if(tmp_props_orig[index]) {
					tmp_props[index] = NULL;
				} else {
					tmp_props.erase(tmp_props.begin() + index);
					tmp_props_orig.erase(tmp_props_orig.begin() + index);
				}
				break;
			}
		}
		updateDatasetPropertyList();
	}
}

void QalculateEditDataSetDialog::nameChanged(const TQString &name) {
	if(name.isNull()) return;
	if(!CALCULATOR->functionNameIsValid(name.ascii())) {
		nameEdit->blockSignals(true);
		nameEdit->setText(CALCULATOR->convertToValidFunctionName(name.ascii()).c_str());
		nameEdit->blockSignals(false);
	}
}


QalculateEditDataPropertyDialog::QalculateEditDataPropertyDialog(TQWidget *parent, const char *name) : KDialogBase(parent, name, true, i18n("Edit Property"), Ok | Cancel, Ok, true) {

	names_edit_dialog = NULL;
	edited_property = NULL;

	setMainWidget(new TQWidget(this));
	TQGridLayout *grid = new TQGridLayout(mainWidget(), 1, 1, 0, spacingHint());
	grid->addWidget(new TQLabel(i18n("Name:"), mainWidget()), 0, 0);
	nameEdit = new KLineEdit(mainWidget());
	grid->addWidget(nameEdit, 0, 1);
	TQHBoxLayout *hbox = new TQHBoxLayout(0, 0, spacingHint());
	grid->addMultiCellLayout(hbox, 1, 1, 0, 1);
	namesLabel = new TQLabel(mainWidget());
	namesLabel->setAlignment(TQt::AlignRight);
	namesLabel->setSizePolicy(TQSizePolicy::Expanding, TQSizePolicy::Preferred);
	hbox->addWidget(namesLabel);
	namesButton = new TQPushButton(i18n("Names Details"), mainWidget());
	hbox->addWidget(namesButton);
	grid->addWidget(new TQLabel(i18n("Descriptive name:"), mainWidget()), 2, 0);
	titleEdit = new KLineEdit(mainWidget());
	grid->addWidget(titleEdit, 2, 1);
	grid->addWidget(new TQLabel(i18n("Description:"), mainWidget()), 3, 0);
	descriptionEdit = new KTextEdit(mainWidget());
	descriptionEdit->setTextFormat(TQTextEdit::PlainText);
	grid->addMultiCellWidget(descriptionEdit, 4, 4, 0, 1);
	grid->addWidget(new TQLabel(i18n("Value type:"), mainWidget()), 5, 0);
	typeCombo = new KComboBox(mainWidget());
	typeCombo->setEditable(false);
	typeCombo->insertItem(i18n("Text"));
	typeCombo->insertItem(i18n("Number"));
	typeCombo->insertItem(i18n("Expression"));
	grid->addWidget(typeCombo, 5, 1);
	hideButton = new TQCheckBox(i18n("Hide"), mainWidget());
	grid->addWidget(hideButton, 6, 0);
	//Use as a unique data set key
	keyButton = new TQCheckBox(i18n("Use as key"), mainWidget());
	grid->addWidget(keyButton, 6, 1);
	approximateButton = new TQCheckBox(i18n("Approximate value"), mainWidget());
	grid->addWidget(approximateButton, 7, 0);
	caseButton = new TQCheckBox(i18n("Case sensitive value"), mainWidget());
	grid->addWidget(caseButton, 7, 1);
	bracketsButton = new TQCheckBox(i18n("Value uses brackets"), mainWidget());
	grid->addWidget(bracketsButton, 8, 0);
	grid->addWidget(new TQLabel(i18n("Unit expression:"), mainWidget()), 9, 0);
	unitEdit = new KLineEdit(mainWidget());
	grid->addWidget(unitEdit, 9, 1);

	connect(namesButton, TQ_SIGNAL(clicked()), this, TQ_SLOT(editNames()));

}

QalculateEditDataPropertyDialog::~QalculateEditDataPropertyDialog() {}

void QalculateEditDataPropertyDialog::slotOk() {

	std::string str = nameEdit->text().ascii();
	remove_blank_ends(str);
	if(str.empty() && (!names_edit_dialog || names_edit_dialog->isEmpty())) {
		//no name -- open dialog again
		nameEdit->setFocus();
		KMessageBox::error(this, i18n("Empty name field"));
		return;
	}
	DataProperty *dp = edited_property;
	dp->setTitle(titleEdit->text().ascii());
	dp->setUnit(unitEdit->text().ascii());
		
	dp->setHidden(hideButton->isChecked());
	dp->setKey(keyButton->isChecked());
	dp->setApproximate(approximateButton->isChecked());
	dp->setCaseSensitive(caseButton->isChecked());
	dp->setUsesBrackets(bracketsButton->isChecked());

	dp->setDescription(descriptionEdit->text().ascii());
		
	switch(typeCombo->currentItem()) {
		case 0: {
			dp->setPropertyType(PROPERTY_STRING);
			break;
		}
		case 1: {
			dp->setPropertyType(PROPERTY_NUMBER);
			break;
		}
		case 2: {
			dp->setPropertyType(PROPERTY_EXPRESSION);
			break;
		}
	}
	if(names_edit_dialog) {
		names_edit_dialog->saveNames(dp, str.c_str());
	} else {
		dp->setName(str, 1);
	}
	edited_property = dp;
	accept();

}

bool QalculateEditDataPropertyDialog::editDataProperty(DataProperty *dp, bool newdp) {

	nameEdit->setFocus();

	if(names_edit_dialog) {
		delete names_edit_dialog;
		names_edit_dialog = NULL;
	}
	edited_property = dp;
	if(!newdp) {
		setCaption(i18n("Edit Property"));
	} else {
		setCaption(i18n("New Property"));
	}

	actionButton(Ok)->setEnabled(true);

	nameEdit->setText(dp->getName().c_str());
	if(dp->countNames() > 1) {
		TQString str = "+ ";
		for(size_t i = 2; i <= dp->countNames(); i++) {
			if(i > 2) str += ", ";
			str += dp->getName(i).c_str();
		}
		namesLabel->setText(str);
	} else {
		namesLabel->clear();
	}

	titleEdit->setText(dp->title(false).c_str());
	unitEdit->setText(dp->getUnitString().c_str());

	hideButton->setChecked(dp->isHidden());
	keyButton->setChecked(dp->isKey());
	approximateButton->setChecked(dp->isApproximate());
	caseButton->setChecked(dp->isCaseSensitive());
	bracketsButton->setChecked(dp->usesBrackets());
	
	descriptionEdit->setText(dp->description().c_str());

	switch(dp->propertyType()) {	
		case PROPERTY_STRING: {
			typeCombo->setCurrentItem(0);
			break;
		}
		case PROPERTY_NUMBER: {
			typeCombo->setCurrentItem(1);
			break;
		}
		case PROPERTY_EXPRESSION: {
			typeCombo->setCurrentItem(2);
			break;
		}
	}

	if(exec() == TQDialog::Accepted) {
		edited_property = NULL;
		return true;
	}
	edited_property = NULL;
	return false;
}

void QalculateEditDataPropertyDialog::editNames() {
	if(!names_edit_dialog) {
		names_edit_dialog = new QalculateEditDataPropertyNamesDialog(this);
		names_edit_dialog->setNames(edited_property, nameEdit->text(), false);
	} else {
		names_edit_dialog->setNames(edited_property, nameEdit->text(), true);
	}
	names_edit_dialog->exec();
	names_edit_dialog->setNamesLE(nameEdit, namesLabel);
}


QalculateEditDataPropertyNamesDialog::QalculateEditDataPropertyNamesDialog(TQWidget *parent, const char *name) : KDialog(parent, name, true) {

	setCaption(i18n("Edit Names"));

	TQVBoxLayout *layout = new TQVBoxLayout(this, marginHint(), spacingHint());

	namesView = new TDEListView(this);
	namesView->addColumn(i18n("Name"));
	namesView->addColumn(i18n("Reference"));
	namesView->setColumnAlignment(1, TQt::AlignCenter);
	namesView->setSorting(-1);
	namesView->setItemsRenameable(true);
	namesView->setItemsMovable(true);
	layout->addWidget(namesView);

	TQHBoxLayout *buttonLayout = new TQHBoxLayout(layout, spacingHint());
	newButton = new TQPushButton(i18n("New"), this);
	buttonLayout->addWidget(newButton);
	deleteButton = new TQPushButton(i18n("Delete"), this);
	deleteButton->setEnabled(false);
	buttonLayout->addWidget(deleteButton);
	buttonLayout->addItem(new TQSpacerItem(0, 0, TQSizePolicy::Expanding, TQSizePolicy::Minimum));
	buttonClose = new KPushButton(KStdGuiItem::close(), this);
	buttonClose->setAutoDefault(true);
	buttonClose->setDefault(true);
	buttonLayout->addWidget(buttonClose);

	connect(namesView, TQ_SIGNAL(selectionChanged()), this, TQ_SLOT(nameSelectionChanged()));
	connect(buttonClose, TQ_SIGNAL(clicked()), this, TQ_SLOT(accept()));
	connect(newButton, TQ_SIGNAL(clicked()), this, TQ_SLOT(newName()));
	connect(deleteButton, TQ_SIGNAL(clicked()), this, TQ_SLOT(deleteName()));
	connect(namesView, TQ_SIGNAL(clicked(TQListViewItem*, const TQPoint&, int)), this, TQ_SLOT(itemClicked(TQListViewItem*, const TQPoint&, int)));

}

QalculateEditDataPropertyNamesDialog::~QalculateEditDataPropertyNamesDialog() {}

void QalculateEditDataPropertyNamesDialog::newName() {
	ExpressionName name;
	TQListViewItem *i = new TDEListViewItem(namesView, namesView->lastChild(), "", i18n("No"), i18n("No"), i18n("No"), i18n("No"), i18n("No"), i18n("No"), i18n("No"));
	namesView->setSelected(i, true);
	tqApp->processEvents();
	namesView->rename(i, 0);
}

void QalculateEditDataPropertyNamesDialog::setNames(DataProperty *item, const TQString &namestr, bool names_edited) {

	if(!names_edited) {
		deleteButton->setEnabled(false);
		namesView->clear();
	}
	if(!names_edited && item && item->countNames() > 0) {
		TQListViewItem *i_prev = NULL;
		for(size_t index = 1; index <= item->countNames(); index++) {
			TQListViewItem *i = new TDEListViewItem(namesView, i_prev);
			i_prev = i;
			if(item->nameIsReference(index))
				i->setText(1, i18n("Yes"));
			else
				i->setText(1, i18n("No"));
			if(index == 1 && !namestr.isEmpty()) {
				i->setText(0, namestr);
			} else {
				i->setText(0, item->getName(index).c_str());
			}
		}
	} else if(!namestr.isEmpty()) {
		if(names_edited) {
			TQListViewItemIterator it(namesView);
			if(it.current())
				it.current()->setText(0, namestr);
		} else {
			new TDEListViewItem(namesView, namestr, i18n("No"));
		}
	}
}
void QalculateEditDataPropertyNamesDialog::saveNames(DataProperty *item, const TQString &str) {
	item->clearNames();
	TQListViewItemIterator it(namesView);
	if(it.current()) {
		bool b = false;
		while(it.current()) {
			bool ref = (it.current()->text(1) == i18n("Yes"));
			if(b || str.isEmpty())
				item->addName(it.current()->text(0).ascii(), ref);
			else
				item->addName(str.ascii(), ref);
			++it;
			b = true;
		}
	} else {
		item->addName(str.ascii());
	}
}
void QalculateEditDataPropertyNamesDialog::setNamesLE(TQLineEdit *entry, TQLabel *label) {
	int index = 0;
	TQString str;
	TQListViewItemIterator it(namesView);
	while(it.current()) {
		if(index == 0) {
			entry->setText(it.current()->text(0));
		} else {
			if(index == 1) {
				str = "+ ";
			} else {
				str += ", ";
			}
			str += it.current()->text(0);
		}
		++it;
		index++;
	}
	label->setText(str);
}
bool QalculateEditDataPropertyNamesDialog::isEmpty() {
	return namesView->childCount() <= 0;
}

void QalculateEditDataPropertyNamesDialog::deleteName() {
	namesView->removeItem(namesView->selectedItem());
}

void QalculateEditDataPropertyNamesDialog::itemClicked(TQListViewItem *i, const TQPoint &, int c) {
	if(i && c > 0) {
		if(i->text(c) == i18n("Yes"))
			i->setText(c, i18n("No"));
		else
			i->setText(c, i18n("Yes"));
	}
}

void QalculateEditDataPropertyNamesDialog::nameSelectionChanged() {
	deleteButton->setEnabled(namesView->selectedItem() != NULL);
}


#include "qalculateeditdatasetdialog.moc"

