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

#include <vector>
#include <string>
#include <tqlabel.h>
#include <klineedit.h>
#include <tdelocale.h>
#include <tqhbox.h>
#include <tdelistview.h>
#include <tdelocale.h>
#include <tqvbox.h>
#include <tdelistview.h>
#include <tdemessagebox.h>
#include <tqlayout.h>
#include <tqpushbutton.h>
#include <tqsplitter.h>

extern tree_struct unit_cats;
extern std::vector<void*> ia_units;
extern PrintOptions printops;
extern EvaluationOptions evalops;


QalculateConvertUnitsDialog::QalculateConvertUnitsDialog(TQWidget *parent, const char *name) : KDialogBase(parent, name, false, i18n("Convert"), Ok | Apply | Cancel | Details, Ok, true) {

	setButtonText(Details, i18n("Selector"));

	selected_category = "";
	block_unit_convert = true;

	TQVBox *box = makeVBoxMainWidget();
	new TQLabel(i18n("Unit expression:"), box);
	unitExpressionEdit = new KLineEdit(box);
	
	TQVBox *box_d = new TQVBox(this);
	box_d->setSpacing(spacingHint());
	new TQWidget(box_d);
	
	TQSplitter *splitter = new TQSplitter(TQt::Vertical, box_d);
	splitter->setSizePolicy(TQSizePolicy::Expanding, TQSizePolicy::Expanding);
	
	setDetailsWidget(box_d);

	categoryView = new TDEListView(splitter);
	categoryView->addColumn(i18n("Category"));
	categoryView->setRootIsDecorated(false);
	categoryView->setFullWidth(true);

	unitView = new TDEListView(splitter);
	unitView->addColumn(i18n("Unit"));
	unitView->setRootIsDecorated(false);
	unitView->setFullWidth(true);

	unitExpressionEdit->setFocus();
	
	connect(unitView, TQ_SIGNAL(selectionChanged()), this, TQ_SLOT(unitSelected()));
	connect(categoryView, TQ_SIGNAL(selectionChanged()), this, TQ_SLOT(categorySelected()));

}

QalculateConvertUnitsDialog::~QalculateConvertUnitsDialog() {}

void QalculateConvertUnitsDialog::updateUnitTree() {
	unitItems.clear();
	categoryItems.clear();
	categoryView->clear();
	TQListViewItem *i = new TDEListViewItem(categoryView, i18n("All")), *i2;
	categoryItems[i] = i18n("All");
	i->setOpen(true);
	TQString str;
	tree_struct *item, *item2;
	unit_cats.it = unit_cats.items.begin();
	if(unit_cats.it != unit_cats.items.end()) {
		item = &*unit_cats.it;
		++unit_cats.it;
		item->it = item->items.begin();
	} else {
		item = NULL;
	}
	str = "";
	i2 = i;
	while(item) {
		str += "/";
		str += item->item.c_str();
		i = new TDEListViewItem(i2, item->item.c_str());
		i->setOpen(false);
		categoryItems[i] = str;
		if(str == selected_category) {
			categoryView->ensureItemVisible(i);
			categoryView->setSelected(i, true);
		}
		while(item && item->it == item->items.end()) {
			int str_i = str.findRev("/");
			if(str_i < 0) {
				str = "";
			} else {
				str.truncate(str_i);
			}
			item = item->parent;
			i = i->parent();
			i2 = i;
		}
		if(item) {
			item2 = &*item->it;
			if(item->it == item->items.begin())
				i2 = i;
			++item->it;
			item = item2;
			item->it = item->items.begin();
		}
	}
	if(!unit_cats.objects.empty()) {
		//add "Uncategorized" category if there are units without category
		i = new TDEListViewItem(categoryView, i18n("Uncategorized"));
		categoryItems[i] = i18n("Uncategorized");
		if(selected_category == i18n("Uncategorized")) {
			categoryView->ensureItemVisible(i);
			categoryView->setSelected(i, true);
		}
	}
	if(!categoryView->selectedItem()) {
		//if no category has been selected (previously selected has been renamed/deleted), select "All"
		selected_category = i18n("All");
		TQListViewItemIterator it(categoryView);
		if(it.current())
			categoryView->setSelected(it.current(), true);
	}
}

void QalculateConvertUnitsDialog::unitSelected() {
	TQListViewItem *selected = unitView->selectedItem();
	if(selected) {
		Unit *u = unitItems[selected];
		if(!CALCULATOR->stillHasUnit(u)) {
			KMessageBox::error(this, i18n("Unit does not exist anymore."));
			emit unitsChanged();
			return;
		}
		unitExpressionEdit->setText(u->print(false, printops.abbreviate_names, printops.use_unicode_signs, &can_display_unicode_string_function, (void*) unitExpressionEdit).c_str());
		unitView->selectAll(false);
		if(!block_unit_convert) actionButton(Apply)->animateClick();
	}
}

void QalculateConvertUnitsDialog::addUnitTreeItem(Unit *u) {
	TQListViewItem *i = new TDEListViewItem(unitView, u->title(true).c_str());
	unitItems[i] = u;
}


void QalculateConvertUnitsDialog::categorySelected() {
	block_unit_convert = true;
	TQListViewItem *selected = categoryView->selectedItem();
	bool no_cat = false, b_all = false;
	unitView->clear();
	unitItems.clear();
	if(!selected) {
		selected_category = "";
		return;
	}
	selected_category = categoryItems[selected];
	if(selected_category == i18n("All")) {
		b_all = true;
	} else if(selected_category == i18n("Uncategorized")) {
		no_cat = true;
	}
	if(!b_all && !no_cat && selected_category[0] == '/') {
		std::string str = selected_category.ascii();
		str.erase(str.begin());
		for(size_t i = 0; i < CALCULATOR->units.size(); i++) {
			if(CALCULATOR->units[i]->isActive() && !CALCULATOR->units[i]->isHidden() && CALCULATOR->units[i]->category().substr(0, selected_category.length() - 1) == str) {
				addUnitTreeItem(CALCULATOR->units[i]);
			}
		}
	} else {
		std::string str = selected_category.ascii();
		for(size_t i = 0; i < CALCULATOR->units.size(); i++) {
			if(CALCULATOR->units[i]->isActive() && !CALCULATOR->units[i]->isHidden() && (b_all || (no_cat && CALCULATOR->units[i]->category().empty()) || CALCULATOR->units[i]->category() == str)) {
				addUnitTreeItem(CALCULATOR->units[i]);
			}
		}
	}
	block_unit_convert = false;
}


#include "qalculateconvertunitsdialog.moc"
