/***************************************************************************
 *   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 "qalculateimportcsvdialog.h"
#include "qalculate_tde_utils.h"

#include <string>
#include <tqlayout.h>
#include <kurlrequester.h>
#include <klineedit.h>
#include <tqlabel.h>
#include <tqradiobutton.h>
#include <tqcheckbox.h>
#include <tqpushbutton.h>
#include <kcombobox.h>
#include <tqspinbox.h>
#include <tqbuttongroup.h>
#include <tdemessagebox.h>
#include <tdelocale.h>
#include <tdeapplication.h>

extern tree_struct variable_cats;

QalculateImportCSVDialog::QalculateImportCSVDialog(TQWidget *parent, const char *name) : KDialogBase(parent, name, true, i18n("Import CSV File"), Ok | Cancel | Help, Ok, true) {

	setMainWidget(new TQWidget(this));
	TQGridLayout *grid = new TQGridLayout(mainWidget(), 1, 1, 0, spacingHint());
	grid->addWidget(new TQLabel(i18n("File:"), mainWidget()), 0, 0);
	fileEdit = new KURLRequester(mainWidget());
	fileEdit->setMode(KFile::File | KFile::ExistingOnly | KFile::LocalOnly);
	fileEdit->setCaption(i18n("Import CSV File"));
	grid->addWidget(fileEdit, 0, 1);
	grid->addWidget(new TQLabel(i18n("Import as:"), mainWidget()), 1, 0);
	TQHBoxLayout *hbox = new TQHBoxLayout(0, 0, spacingHint());
	grid->addLayout(hbox, 1, 1);
	TQButtonGroup *group = new TQButtonGroup();
	matrixButton = new TQRadioButton(i18n("Matrix"), mainWidget());
	group->insert(matrixButton, 0);
	hbox->addWidget(matrixButton);
	matrixButton->setChecked(true);
	vectorsButton = new TQRadioButton(i18n("Vectors"), mainWidget());
	group->insert(vectorsButton, 1);
	hbox->addWidget(vectorsButton);
	hbox->addItem(new TQSpacerItem(0, 0, TQSizePolicy::Expanding, TQSizePolicy::Minimum));
	grid->addWidget(new TQLabel(i18n("Name:"), mainWidget()), 2, 0);
	nameEdit = new KLineEdit(mainWidget());
	grid->addWidget(nameEdit, 2, 1);
	grid->addWidget(new TQLabel(i18n("Descriptive name:"), mainWidget()), 3, 0);
	titleEdit = new KLineEdit(mainWidget());
	grid->addWidget(titleEdit, 3, 1);
	grid->addWidget(new TQLabel(i18n("Category:"), mainWidget()), 4, 0);
	categoryCombo = new KComboBox(mainWidget());
	categoryCombo->setMaximumWidth(250);
	categoryCombo->setEditable(true);
	grid->addWidget(categoryCombo, 4, 1);
	grid->addWidget(new TQLabel(i18n("First row:"), mainWidget()), 5, 0);
	firstRowBox = new TQSpinBox(1, 1000, 1, mainWidget());
	grid->addWidget(firstRowBox, 5, 1);
	hbox = new TQHBoxLayout(0, 0, spacingHint());
	grid->addMultiCellLayout(hbox, 6, 6, 0, 1);
	hbox->addItem(new TQSpacerItem(0, 0, TQSizePolicy::Expanding, TQSizePolicy::Minimum));
	includesHeadingsButton = new TQCheckBox(i18n("Includes headings"), mainWidget());
	includesHeadingsButton->setChecked(true);
	hbox->addWidget(includesHeadingsButton);
	grid->addWidget(new TQLabel(i18n("Delimiter:"), mainWidget()), 7, 0);
	delimiterCombo = new KComboBox(mainWidget());
	delimiterCombo->setMaximumWidth(250);
	delimiterCombo->insertItem(i18n("Comma"));
	delimiterCombo->insertItem(i18n("Tabulator"));
	delimiterCombo->insertItem(i18n("Semicolon"));
	delimiterCombo->insertItem(i18n("Space"));
	delimiterCombo->insertItem(i18n("Other"));
	delimiterCombo->setEditable(false);
	grid->addWidget(delimiterCombo, 7, 1);
	otherDelimiterEdit = new KLineEdit(mainWidget());
	grid->addWidget(otherDelimiterEdit, 8, 1);
	otherDelimiterEdit->setEnabled(false);

	connect(delimiterCombo, TQ_SIGNAL(activated(int)), this, TQ_SLOT(delimiterChanged(int)));
	connect(nameEdit, TQ_SIGNAL(textChanged(const TQString&)), this, TQ_SLOT(nameChanged(const TQString&)));

}

QalculateImportCSVDialog::~QalculateImportCSVDialog() {
}

void QalculateImportCSVDialog::slotHelp() {
	TDEApplication::kApplication()->invokeHelp("qalculate-import-export-csv");
}

void QalculateImportCSVDialog::delimiterChanged(int i) {
	otherDelimiterEdit->setEnabled(i == 4);
}

void QalculateImportCSVDialog::slotOk() {

	TQString str = fileEdit->url().stripWhiteSpace();
	if(str.isEmpty()) {
		//no name -- open dialog again
		fileEdit->setFocus();
		KMessageBox::error(this, i18n("No file name entered."));
		return;
	}
	std::string delimiter = "";
	switch(delimiterCombo->currentItem()) {
		case 0: {
			delimiter = ",";
			break;
		}
		case 1: {
			delimiter = "\t";
			break;
		}			
		case 2: {
			delimiter = ";";
			break;
		}		
		case 3: {
			delimiter = " ";
			break;
		}				
		case 4: {
			delimiter = otherDelimiterEdit->text().ascii();
			break;
		}			
	}
	if(delimiter.empty()) {
		//no delimiter -- open dialog again
		otherDelimiterEdit->setFocus();
		KMessageBox::error(this, i18n("No delimiter selected."));
		return;
	}
	if(!CALCULATOR->importCSV(str.ascii(), firstRowBox->value(), includesHeadingsButton->isChecked(), delimiter, matrixButton->isChecked(), nameEdit->text().ascii(), titleEdit->text().ascii(), categoryCombo->lineEdit()->text().ascii())) {
		KMessageBox::error(this, i18n("An error occured when importing the CSV file."));
		reject();
	}
	accept();

}

bool QalculateImportCSVDialog::importCSVFile() {

	fileEdit->setFocus();

	nameEdit->clear();
	fileEdit->clear();
	titleEdit->clear();

	//TQStringList cats;
	TQString catstr;
	categoryCombo->clear();
	tree_struct *item, *item2;
	variable_cats.it = variable_cats.items.begin();
	if(variable_cats.it != variable_cats.items.end()) {
		item = &*variable_cats.it;
		++variable_cats.it;
		item->it = item->items.begin();
	} else {
		item = NULL;
	}

	catstr = "";
	while(item) {
		if(!catstr.isEmpty()) catstr += "/";
		catstr += item->item.c_str();
		categoryCombo->insertItem(catstr);
		while(item && item->it == item->items.end()) {
			int str_i = catstr.findRev("/");
			if(str_i < 0) {
				catstr = "";
			} else {
				catstr.truncate(str_i);
			}
			item = item->parent;
		}
		if(item) {
			item2 = &*item->it;
			++item->it;
			item = item2;
			item->it = item->items.begin();	
		}
	}
	
	categoryCombo->lineEdit()->clear();

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

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

#include "qalculateimportcsvdialog.moc"
