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

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

extern MathStructure *mstruct;

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

	setMainWidget(new TQWidget(this));
	TQGridLayout *grid = new TQGridLayout(mainWidget(), 1, 1, 0, spacingHint());
	TQButtonGroup *group = new TQButtonGroup();
	currentResultButton = new TQRadioButton(i18n("Current result"), mainWidget());
	group->insert(currentResultButton, 0);
	grid->addWidget(currentResultButton, 0, 0);
	currentResultButton->setChecked(true);
	matrixVectorButton = new TQRadioButton(i18n("Matrix/vector variable"), mainWidget());
	group->insert(matrixVectorButton, 1);
	grid->addWidget(matrixVectorButton, 1, 0);
	matrixVectorEdit = new KLineEdit(mainWidget());
	grid->addWidget(matrixVectorEdit, 1, 1);
	grid->addWidget(new TQLabel(i18n("File:"), mainWidget()), 2, 0);
	fileEdit = new KURLRequester(mainWidget());
	fileEdit->setMode(KFile::File | KFile::ExistingOnly | KFile::LocalOnly);
	fileEdit->setCaption(i18n("Export CSV File"));
	grid->addWidget(fileEdit, 2, 1);
	grid->addWidget(new TQLabel(i18n("Delimiter:"), mainWidget()), 3, 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, 3, 1);
	otherDelimiterEdit = new KLineEdit(mainWidget());
	grid->addWidget(otherDelimiterEdit, 4, 1);
	otherDelimiterEdit->setEnabled(false);

	connect(group, TQ_SIGNAL(clicked(int)), this, TQ_SLOT(exportSourceChanged(int)));
	connect(delimiterCombo, TQ_SIGNAL(activated(int)), this, TQ_SLOT(delimiterChanged(int)));

}

QalculateExportCSVDialog::~QalculateExportCSVDialog() {}

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

void QalculateExportCSVDialog::exportSourceChanged(int i) {
	matrixVectorEdit->setEnabled(i == 1);
}
void QalculateExportCSVDialog::delimiterChanged(int i) {
	otherDelimiterEdit->setEnabled(i == 4);
}
void QalculateExportCSVDialog::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;
	}
	MathStructure *matrix_struct;
	if(export_variable) {
		matrix_struct = (MathStructure*) &export_variable->get();
	} else if(currentResultButton->isChecked()) {
		matrix_struct = mstruct;
	} else {
		std::string str2 = matrixVectorEdit->text().ascii();
		remove_blank_ends(str2);
		if(str2.empty()) {
			matrixVectorEdit->setFocus();
			KMessageBox::error(this, i18n("No variable name entered."));
			return;
		}
		Variable *var = CALCULATOR->getActiveVariable(str2);
		if(!var || !var->isKnown()) {
			var = CALCULATOR->getVariable(str2);
			while(var && !var->isKnown()) {
				var = CALCULATOR->getVariable(str2);
			}
		}
		if(!var || !var->isKnown()) {
			matrixVectorEdit->setFocus();
			KMessageBox::error(this, i18n("No known variable with entered name found."));
			return;
		}
		matrix_struct = (MathStructure*) &((KnownVariable*) var)->get();
	}		
	if(!CALCULATOR->exportCSV(*matrix_struct, str.ascii(), delimiter)) {
		TQString error_str;
		error_str.sprintf(i18n("Could not export to file \n%s").utf8(), str.ascii());
		KMessageBox::error(this, error_str);
		reject();
	}
	accept();

}

void QalculateExportCSVDialog::exportCSVFile(KnownVariable *v) {

	fileEdit->setFocus();
	
	export_variable = v;

	if(v) {
		fileEdit->setURL(v->preferredDisplayName(false, false, false, false, &can_display_unicode_string_function, (void*) fileEdit->lineEdit()).name.c_str());
		matrixVectorEdit->setText(v->preferredDisplayName(false, false, false, false, &can_display_unicode_string_function, (void*) matrixVectorEdit).name.c_str());
		matrixVectorButton->setChecked(true);
	} else {
		fileEdit->clear();
		matrixVectorEdit->clear();
		currentResultButton->setChecked(true);
	}
	currentResultButton->setEnabled(v == NULL);
	matrixVectorButton->setEnabled(v == NULL);
	matrixVectorEdit->setEnabled(false);

	exec();
	
}


#include "qalculateexportcsvdialog.moc"
