#include <iostream>

#include "exportoofiledialog.h"

ExportOOFileDialog::ExportOOFileDialog():QFileDialog()
{
	init();
}

ExportOOFileDialog::ExportOOFileDialog (QWidget * parent, const char* name, bool modal):QFileDialog(parent, name,modal)
{
	init();
}

bool ExportOOFileDialog::foundConfig()
{
	return !filters.isEmpty();
}

QString ExportOOFileDialog::selectedConfig()
{
	QStringList::Iterator itpath=configPaths.begin();
	QStringList::Iterator itf=filters.begin();
	while (itf != filters.end()) 
	{
		if (*itf==lastFilter) return *itpath;
		itpath++;	
		itf++;
    }
	qWarning ("ExportOOFileDialog::selectedConfig  No filter found!");
	return "";
}

void ExportOOFileDialog::newConfigPath(const QString &s)
{
	lastFilter=s;
}

QString ExportOOFileDialog::selectedFile()
{
	return QFileDialog::selectedFile();
}


void ExportOOFileDialog::addFilter(const QString &f)
{
	lastFilter=f;
	filters.append (f);
	QFileDialog::addFilter (f);
}

void ExportOOFileDialog::init()
{
	setMode( QFileDialog::AnyFile );
	QDir d;
	d.setPath ("/usr/share/vym/exports");
	scanExportConfigs(d);
	d.setPath (d.homeDirPath()+"/.vym/exports");
	scanExportConfigs(d);
	d.setPath ("exports");
	scanExportConfigs(d);

	connect (
		this,SIGNAL (filterSelected(const QString&)),
		this, SLOT( newConfigPath(const QString &)));
}

void ExportOOFileDialog::scanExportConfigs(QDir d)
{
	// Scan existing export configurations
	SimpleSettings set;
	QFile f;
	if (d.exists())
	{
		// Traverse files
		d.setFilter( QDir::Files| QDir::Hidden | QDir::NoSymLinks );
		const QFileInfoList *filelist = d.entryInfoList();
		QFileInfoListIterator itfile( *filelist );
		QFileInfo *fi;

		while ( (fi = itfile.current()) != 0 ) 
		{
			if (fi->fileName().endsWith(".conf") )
			{
				configPaths.append (fi->absFilePath());
				set.clear();
				set.readSettings (fi->absFilePath());
				addFilter (set.readEntry("Name") + " (*.odp)");
			}		
			++itfile;
		}	
	}		
}
