/***************************************************************************
 *   Copyright (C) 2005 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 "qalculateinsertmatrixvectordialog.h"
#include "qalculate_tde_utils.h"

#include <tqtable.h>
#include <tqgrid.h>
#include <klineedit.h>
#include <tqpushbutton.h>
#include <kcombobox.h>
#include <tqlabel.h>
#include <tdelocale.h>
#include <tqvbox.h>
#include <tqhbox.h>
#include <tqcheckbox.h>
#include <tdemessagebox.h>
#include <tqspinbox.h>
#include <tqlayout.h>
#include <tqbuttongroup.h>
#include <tqradiobutton.h>
#include <tdeapplication.h>
#include <tdeversion.h>
#include <kstdguiitem.h>

extern PrintOptions printops;

class QalculateInsertMatrixTableItem : public TQTableItem {

public:
		
	QalculateInsertMatrixTableItem(TQTable *table);
	QalculateInsertMatrixTableItem(TQTable *table, const TQString & text);

	int alignment() const;
	
};

class QalculateInsertMatrixTable : public TQTable {

	public:
		
		QalculateInsertMatrixTable(TQWidget *parent = 0, const char *name = 0) : TQTable(parent, name) {}
		QalculateInsertMatrixTable(int numRows, int numCols, TQWidget *parent = 0, const char *name = 0) : TQTable(numRows, numCols, parent, name) {}

		TQWidget *beginEdit(int row, int col, bool replace) {
			TQWidget *w = TQTable::beginEdit(row, col, replace);
			((TQLineEdit*) w)->selectAll();
			return w;
		}
	
};


QalculateInsertMatrixVectorDialog::QalculateInsertMatrixVectorDialog(TQWidget *parent, const char *name) : KDialogBase(parent, name, true, i18n("Edit Variable"), Ok | Cancel | User1, Ok, true, KGuiItem(i18n("Insert Selection"))) {

	setMainWidget(new TQWidget(this));
	TQGridLayout *grid = new TQGridLayout(mainWidget(), 1, 1, 0, spacingHint());
	grid->addWidget(new TQLabel(i18n("Rows:"), mainWidget()), 0, 0);
	rowsBox = new TQSpinBox(1, 1000, 1, mainWidget());
	grid->addWidget(rowsBox, 0, 1);
	grid->addWidget(new TQLabel(i18n("Columns:"), mainWidget()), 1, 0);
	columnsBox = new TQSpinBox(1, 1000, 1, mainWidget());
	grid->addWidget(columnsBox, 1, 1);
	TQHBoxLayout *hbox = new TQHBoxLayout(0, 0, spacingHint());
	grid->addMultiCellLayout(hbox, 2, 2, 0, 1);
	hbox->addItem(new TQSpacerItem(0, 0, TQSizePolicy::Expanding, TQSizePolicy::Minimum));
	TQButtonGroup *group = new TQButtonGroup();
	matrixButton = new TQRadioButton(i18n("Matrix"), mainWidget());
	group->insert(matrixButton, 0);
	hbox->addWidget(matrixButton);
	vectorButton = new TQRadioButton(i18n("Vector"), mainWidget());
	group->insert(vectorButton, 1);
	hbox->addWidget(vectorButton);
	elementsLabel = new TQLabel(i18n("Elements:"), mainWidget());
	grid->addMultiCellWidget(elementsLabel, 3, 3, 0, 1);
	elementsTable = new QalculateInsertMatrixTable(0, 0, mainWidget());
	grid->addMultiCellWidget(elementsTable, 4, 4, 0, 1);
	elementsTable->setSelectionMode(TQTable::Single);
	
	insertSelectionButton = actionButton(User1);
	onSelectionChanged();

	connect(insertSelectionButton, SIGNAL(clicked()), this, SLOT(insertSelection()));
	connect(elementsTable, SIGNAL(selectionChanged()), this, SLOT(onSelectionChanged()));
	connect(rowsBox, SIGNAL(valueChanged(int)), this, SLOT(rowsChanged(int)));
	connect(columnsBox, SIGNAL(valueChanged(int)), this, SLOT(columnsChanged(int)));
	connect(group, SIGNAL(clicked(int)), this, SLOT(typeChanged(int)));

}

QalculateInsertMatrixVectorDialog::~QalculateInsertMatrixVectorDialog() {}

void QalculateInsertMatrixVectorDialog::onSelectionChanged() {
	insertSelectionButton->setEnabled(elementsTable->currentSelection() >= 0);
}
void QalculateInsertMatrixVectorDialog::typeChanged(int i) {
	if(i == 0) {
		elementsLabel->setText(i18n("Elements:"));
		bool b = true;
		for(int index_r = elementsTable->numRows() - 1; index_r >= 0 && b; index_r--) {
			for(int index_c = elementsTable->numCols() - 1; index_c >= 0; index_c--) {
				if(elementsTable->text(index_r, index_c).isEmpty()) {
					elementsTable->setText(index_r, index_c, "0");
				} else {
					b = false;
					break;
				}
			}
		}
	} else {
		elementsLabel->setText(i18n("Elements (in horizontal order):"));
	}
}
void QalculateInsertMatrixVectorDialog::rowsChanged(int i) {
	int r = elementsTable->numRows();
	elementsTable->setNumRows(i);
	bool b = matrixButton->isChecked();
	for(int index_r = r; index_r < i; index_r++) {
		for(int index_c = 0; index_c < elementsTable->numCols(); index_c++) {
			if(b) elementsTable->setItem(index_r, index_c, new QalculateInsertMatrixTableItem(elementsTable, "0"));
			else elementsTable->setItem(index_r, index_c, new QalculateInsertMatrixTableItem(elementsTable));
		}
	}
}
void QalculateInsertMatrixVectorDialog::columnsChanged(int i) {
	int c = elementsTable->numCols();
	elementsTable->setNumCols(i);
	bool b = matrixButton->isChecked();
	for(int index_r = 0; index_r < elementsTable->numRows(); index_r++) {
		for(int index_c = c; index_c < i; index_c++) {
			if(b) elementsTable->setItem(index_r, index_c, new QalculateInsertMatrixTableItem(elementsTable, "0"));
			else elementsTable->setItem(index_r, index_c, new QalculateInsertMatrixTableItem(elementsTable));
		}
	}
}

TQString QalculateInsertMatrixVectorDialog::newVector() {
	return editMatrixVector(NULL, true);
}
TQString QalculateInsertMatrixVectorDialog::newMatrix() {
	return editMatrixVector(NULL, false);
}

void QalculateInsertMatrixVectorDialog::slotOk() {
	int r = rowsBox->value();
	int c = columnsBox->value();
	if(vectorButton->isChecked()) {
		bool b = false;
		matrixstr = "[";
		for(int index_r = 0; index_r < r; index_r++) {
			for(int index_c = 0; index_c < c; index_c++) {
				if(!elementsTable->text(index_r, index_c).isEmpty()) {
					TQString str2 = elementsTable->text(index_r, index_c).stripWhiteSpace();
					if(!str2.isEmpty()) {
						if(b) {
							matrixstr += CALCULATOR->getComma().c_str();
							matrixstr += " ";
						} else {
							b = true;
						}
						matrixstr += str2;
					}
				}
			}
		}
		matrixstr += "]";
	} else {
		matrixstr = "[";
		bool b1 = false;
		for(int index_r = 0; index_r < r; index_r++) {
			if(b1) {
				matrixstr += CALCULATOR->getComma().c_str();
				matrixstr += " ";
			} else {
				b1 = true;
			}
			matrixstr += "[";
			bool b2 = false;
			for(int index_c = 0; index_c < c; index_c++) {
				if(b2) {
					matrixstr += CALCULATOR->getComma().c_str();
					matrixstr += " ";
				} else {
					b2 = true;
				}
				matrixstr += elementsTable->text(index_r, index_c).stripWhiteSpace();				
			}
			matrixstr += "]";
		}
		matrixstr += "]";
	}					
	accept();
}
void QalculateInsertMatrixVectorDialog::insertSelection() {
	TQTableSelection sel = elementsTable->selection(elementsTable->currentSelection());
	if(vectorButton->isChecked()) {
		bool b = false;
		matrixstr = "[";
		for(int index_r = sel.topRow(); index_r <= sel.bottomRow(); index_r++) {
			for(int index_c = sel.leftCol(); index_c <= sel.rightCol(); index_c++) {
				if(!elementsTable->text(index_r, index_c).isEmpty()) {
					TQString str2 = elementsTable->text(index_r, index_c).stripWhiteSpace();
					if(!str2.isEmpty()) {
						if(b) {
							matrixstr += CALCULATOR->getComma().c_str();
							matrixstr += " ";
						} else {
							b = true;
						}
						matrixstr += str2;
					}
				}
			}
		}
		matrixstr += "]";
	} else {
		matrixstr = "[";
		bool b1 = false;
		for(int index_r = sel.topRow(); index_r <= sel.bottomRow(); index_r++) {
			if(b1) {
				matrixstr += CALCULATOR->getComma().c_str();
				matrixstr += " ";
			} else {
				b1 = true;
			}
			matrixstr += "[";
			bool b2 = false;
			for(int index_c = sel.leftCol(); index_c <= sel.rightCol(); index_c++) {
				if(b2) {
					matrixstr += CALCULATOR->getComma().c_str();
					matrixstr += " ";
				} else {
					b2 = true;
				}
				matrixstr += elementsTable->text(index_r, index_c).stripWhiteSpace();				
			}
			matrixstr += "]";
		}
		matrixstr += "]";
	}					
	accept();
}

TQString QalculateInsertMatrixVectorDialog::editMatrixVector(const MathStructure *initial_value, bool create_vector, bool is_text_struct, bool is_result) {

	if(initial_value && !initial_value->isVector()) {
		return NULL;
	}

	if(initial_value) {
		create_vector = !initial_value->isMatrix();
	}
	if(create_vector) {
		vectorButton->setChecked(true);
		elementsLabel->setText(i18n("Elements (in horizontal order):"));
	} else {
		matrixButton->setChecked(true);
		elementsLabel->setText(i18n("Elements:"));
	}

	if(is_result) {
#if TDE_VERSION_MAJOR < 4 && TDE_VERSION_MINOR < 2
		setButtonOKText(i18n("Insert"));
		setButtonCancelText(KStdGuiItem::close().text());
#else
#if TDE_VERSION_MAJOR < 4 && TDE_VERSION_MINOR < 3
		setButtonOK(KGuiItem(i18n("Insert")));
#else
		setButtonOK(KStdGuiItem::insert());	
#endif
		setButtonCancel(KStdGuiItem::close());
#endif		
		actionButton(Cancel)->setDefault(true);
		actionButton(Cancel)->setFocus();
		if(create_vector) {
			setCaption(i18n("Vector Result"));
		} else {
			setCaption(i18n("Matrix Result"));
		}
	} else {
#if TDE_VERSION_MAJOR < 4 && TDE_VERSION_MINOR < 2
		setButtonOKText(KStdGuiItem::ok().text());
		setButtonCancelText(KStdGuiItem::cancel().text());
#else
		setButtonOK(KStdGuiItem::ok());
		setButtonCancel(KStdGuiItem::cancel());
#endif	
		actionButton(Ok)->setDefault(true);
		elementsTable->setFocus();
		if(create_vector) {
			setCaption(i18n("Vector"));
		} else {
			setCaption(i18n("Matrix"));
		}
	}

	int r = 4, c = 4;
	if(create_vector) {
		if(initial_value) {
			r = initial_value->countChildren();
			c = (int) ::sqrt(r) + 4;
			if(r % c > 0) {
				r = r / c + 1;
			} else {
				r = r / c;
			}
		} else {
			c = 4;
			r = 4;
		}
	} else if(initial_value) {
		c = initial_value->columns();
		r = initial_value->rows();
	}

	rowsBox->setValue(r);
	columnsBox->setValue(c);
	elementsTable->setNumRows(r);
	elementsTable->setNumCols(c);

	int timeout;
	if(initial_value) timeout = 3000 / (r * c);
	else timeout = 3000;
	printops.can_display_unicode_string_arg = (void*) elementsTable;
	for(int index_r = 0; index_r < r; index_r++) {
		for(int index_c = 0; index_c < c; index_c++) {
			if(create_vector) {
				if(initial_value && index_r * c + index_c < (int) initial_value->countChildren()) {
					if(is_text_struct) elementsTable->setText(index_r, index_c, initial_value->getChild(index_r * c + index_c + 1)->symbol().c_str());
					else elementsTable->setText(index_r, index_c, initial_value->getChild(index_r * c + index_c + 1)->print(printops).c_str());
				} else {
					elementsTable->setText(index_r, index_c, "");
				}
			} else {
				if(initial_value) {
					if(is_text_struct) elementsTable->setText(index_r, index_c, initial_value->getElement(index_r + 1, index_c + 1)->symbol().c_str());
					else elementsTable->setText(index_r, index_c, initial_value->getElement(index_r + 1, index_c + 1)->print(printops).c_str());
				} else {
					elementsTable->setText(index_r, index_c, "0");
				}
			}
		}
	}
	printops.can_display_unicode_string_arg = NULL;
	matrixstr = "";
	
	onSelectionChanged();

	exec();

	return matrixstr;
}

#if TQT_VERSION >= 0x030200
QalculateInsertMatrixTableItem::QalculateInsertMatrixTableItem(TQTable *table) : TQTableItem(table, TQTableItem::OnTyping) {}
#else
QalculateInsertMatrixTableItem::QalculateInsertMatrixTableItem(TQTable *table) : TQTableItem(table, TQTableItem::OnTyping, TQString::null) {}
#endif
QalculateInsertMatrixTableItem::QalculateInsertMatrixTableItem(TQTable *table, const TQString & text) : TQTableItem(table, TQTableItem::OnTyping, text) {}

int QalculateInsertMatrixTableItem::alignment() const {return TQt::AlignRight;}

#include "qalculateinsertmatrixvectordialog.moc"

