/* This file is part of the KDE project
   Copyright (C) 2001 Joseph Wenninger <jowenn@kde.org>

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License as published by the Free Software Foundation; either
   version 2 of the License, or (at your option) any later version.

   This library 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
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
*/

#include "KWQtSqlPowerSerialDataSource.h"
#include "KWQtSqlPowerSerialDataSource.moc"
#include "KWQtSqlMailMergeOpen.h"
#include <tqlayout.h>
#include <tqdom.h>
#include <kcombobox.h>
#include <klineedit.h>
#include <kpushbutton.h>
#include <tqsqldatabase.h>
#include <tqmessagebox.h>
#include <kpassdlg.h>
#include <tqsqlrecord.h>
#include <tqsqlcursor.h>
#include <tqdatatable.h>
#include <kdebug.h>

#define KWQtSqlBarIcon( x ) BarIcon( x, db->KWInstance() )

/******************************************************************
 *
 * Class: KWQtSqlSerialDataSource
 *
 ******************************************************************/

KWQtSqlPowerSerialDataSource::KWQtSqlPowerSerialDataSource(TDEInstance *inst,TQObject *parent)
	: KWQtSqlSerialDataSourceBase(inst,parent),myquery(0)
{
	port=i18n("default");
}

KWQtSqlPowerSerialDataSource::~KWQtSqlPowerSerialDataSource()
{
	if (myquery) delete myquery;
	TQSqlDatabase::removeDatabase("KWTQTSQLPOWER");
}

void KWQtSqlPowerSerialDataSource::refresh(bool force)
{
	if ((force) || (myquery==0))
	{
		if (myquery)
		{
			delete myquery;
			myquery=0;
		}
		TQString tmp=query.upper();
		if (!tmp.startsWith("SELECT")) return;
		if ((!database) || (!database->isOpen()))openDatabase();
		myquery=new KWMySqlCursor(query,true,database);
		myquery->setMode(TQSqlCursor::ReadOnly);
	}
	kdDebug()<<TQString("There were %1 rows in the query").arg(myquery->size())<<endl;
}

TQString KWQtSqlPowerSerialDataSource::getValue( const TQString &name, int record ) const
{
	int num=record;

	if (!myquery) return name;
	if ( num < 0 || num > (int)myquery->size() )
		return name;
	if (!myquery->seek(num,false)) return i18n(">>>Illegal position within datasource<<<");
	if (!myquery->contains(name)) return i18n(">>>Field %1 is unknown in the current database query<<<").arg(name);
	return (myquery->value(name)).toString();
}

void KWQtSqlPowerSerialDataSource::save( TQDomDocument &doc, TQDomElement &parent)
{
        TQDomElement def=doc.createElement(TQString::fromLatin1("DEFINITION"));
        parent.appendChild(def);
        {
                TQDomElement defEnt=doc.createElement(TQString::fromLatin1("DATABASE"));
                defEnt.setAttribute(TQString::fromLatin1("hostname"),hostname);
                defEnt.setAttribute(TQString::fromLatin1("port"),port);
                defEnt.setAttribute(TQString::fromLatin1("driver"),driver);
                defEnt.setAttribute(TQString::fromLatin1("databasename"),databasename);
                defEnt.setAttribute(TQString::fromLatin1("username"),username);
                def.appendChild(defEnt);

		defEnt=doc.createElement(TQString::fromLatin1("QUERY"));
		defEnt.setAttribute(TQString::fromLatin1("value"),query);
		def.appendChild(defEnt);

		TQDomElement sampleEnt=doc.createElement(TQString::fromLatin1("SAMPLERECORD"));
		parent.appendChild(sampleEnt);
	        for (DbRecord::Iterator it=sampleRecord.begin();it!=sampleRecord.end();++it)
        	{
                	TQDomElement fieldEnt=doc.createElement(TQString::fromLatin1("FIELD"));
	                fieldEnt.setAttribute(TQString::fromLatin1("name"),it.key());
	                sampleEnt.appendChild(fieldEnt);
	        }
        }
}

void KWQtSqlPowerSerialDataSource::load( TQDomElement& parentElem )
{
        clearSampleRecord();
        TQDomNode defNd=parentElem.namedItem("DEFINITION");
        if (!defNd.isNull())
	{
	        TQDomElement def=defNd.toElement();
		TQDomNode dbNd=def.namedItem("DATABASE");
		if (!dbNd.isNull())
		{
			TQDomElement dbEnt=dbNd.toElement();
			if (dbEnt.tagName()==TQString::fromLatin1("DATABASE"))
			{
				hostname=dbEnt.attribute(TQString::fromLatin1("hostname"));
				port=dbEnt.attribute(TQString::fromLatin1("port"));
				driver=dbEnt.attribute(TQString::fromLatin1("driver"));
				databasename=dbEnt.attribute(TQString::fromLatin1("databasename"));
				username=dbEnt.attribute(TQString::fromLatin1("username"));
			}
		}
		TQDomNode queryNd=def.namedItem("QUERY");
		if (!queryNd.isNull())
		{
			query=queryNd.toElement().attribute(TQString::fromLatin1("value"));
		}
        }

        defNd=parentElem.namedItem("SAMPLERECORD");
        if (!defNd.isNull())
	{
		TQDomElement def1=defNd.toElement();
	        for (TQDomElement defEnt=defNd.firstChild().toElement();!defEnt.isNull();defEnt=defEnt.nextSibling().toElement())
	        {
	               addSampleRecordEntry(defEnt.attribute(TQString::fromLatin1("name")));
	        }
	}
}

bool KWQtSqlPowerSerialDataSource::showConfigDialog(TQWidget *par,int action)
{
   bool ret=false;
   if (action==KWSLEdit)
   {
        if ((!database) || (!database->isOpen()))openDatabase();
	KWQtSqlPowerMailMergeEditor *dia=new KWQtSqlPowerMailMergeEditor(par,this);
	ret=dia->exec();
	delete dia;
   }
	else ret=KWQtSqlSerialDataSourceBase::showConfigDialog(par,action);
   return ret;
}

void KWQtSqlPowerSerialDataSource::clearSampleRecord() {sampleRecord.clear();}

void KWQtSqlPowerSerialDataSource::addSampleRecordEntry(TQString name)
{sampleRecord[name]=name; }//i18n("No Value");}


/******************************************************************
 *
 * Class: KWQtSqlMailMergeEditor
 *
 ******************************************************************/

KWQtSqlPowerMailMergeEditor::KWQtSqlPowerMailMergeEditor( TQWidget *parent, KWQtSqlPowerSerialDataSource *db_ )
	:KDialogBase( Plain, i18n( "Mail Merge - Editor" ), Ok | Cancel, Ok, parent, "", true ), db( db_ )
{
        (new TQVBoxLayout(plainPage()))->setAutoAdd(true);
        setMainWidget(widget=new KWQtSqlPowerWidget(plainPage()));
	connect(widget->setup,TQT_SIGNAL(clicked()),this,TQT_SLOT(openSetup()));
	connect(widget->tables,TQT_SIGNAL(currentChanged(TQListBoxItem*)),this,TQT_SLOT(slotTableChanged(TQListBoxItem*)));
	connect(widget->execute,TQT_SIGNAL(clicked()),this,TQT_SLOT(slotExecute()));
	connect(this,TQT_SIGNAL(okClicked()),this,TQT_SLOT(slotSetQuery()));
	widget->query->setText(db->query);
	updateDBViews();
}

void KWQtSqlPowerMailMergeEditor::slotSetQuery()
{
	db->query=widget->query->text();
	db->refresh(true);
}

void KWQtSqlPowerMailMergeEditor::slotExecute()
{
	if (!db->database) if (!db->openDatabase()) return;
	TQString tmp=widget->query->text().upper();
	if (!tmp.startsWith("SELECT")) return;
	KWMySqlCursor *cur=new KWMySqlCursor(widget->query->text(),true,db->database);
	cur->setMode(TQSqlCursor::ReadOnly);

	db->clearSampleRecord();
	kdDebug()<<TQString("Fieldname count %1").arg(cur->count())<<endl;
	for (uint i=0;i<cur->count();i++)
		db->addSampleRecordEntry(cur->fieldName(i));

	widget->queryresult->setSqlCursor(cur,true,true);
	widget->queryresult->refresh(TQDataTable::RefreshAll);
}

void KWQtSqlPowerMailMergeEditor::slotTableChanged ( TQListBoxItem * item )
{
	widget->fields->clear();
	if (item)
	{
		if (!db->database) return;
		TQSqlRecord rec=db->database->record(item->text());
		for (uint i=0;i<rec.count();i++)
		{
			widget->fields->insertItem(rec.fieldName(i));
		}
	}
}

void KWQtSqlPowerMailMergeEditor::openSetup()
{
        KWQtSqlMailMergeOpen *dia=new KWQtSqlMailMergeOpen(this,db);
        if (dia->exec())
	{
		 db->openDatabase();
		 updateDBViews();
	}
        delete dia;
}


void KWQtSqlPowerMailMergeEditor::updateDBViews()
{
	widget->fields->clear();
	widget->tables->clear();
	if (!db->database) return;
	widget->tables->insertStringList(db->database->tables());
}

KWQtSqlPowerMailMergeEditor::~KWQtSqlPowerMailMergeEditor(){;}


extern "C" {
        KWORD_MAILMERGE_EXPORT KWMailMergeDataSource *create_kwmailmerge_qtsqldb_power(TDEInstance *inst,TQObject *parent)
        {
                return new KWQtSqlPowerSerialDataSource(inst,parent);
        }
}
