/***************************************************************************
 *   Copyright (C) 2004 by Kazuki Ohta                                     *
 *   mover@hct.zaq.ne.jp                                                   *
 *                                                                         *
 *   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 "kkaddressbookdialog.h"
#include "kknewcontactdialog.h"
#include "kkcontactdata.h"
#include "kkcontactquicksearchline.h"
#include "kksetupgroupdialog.h"
//#include "../kkview.h"
#include "contactxml.h"

#include <qlabel.h>
#include <qlayout.h>
#include <qsplitter.h>
#include <qframe.h>
#include <qtoolbutton.h>
#include <qvbox.h>
#include <qhbox.h>
#include <qheader.h>
#include <qtextstream.h>
#include <qdom.h>
#include <qfile.h>
#include <qtooltip.h>

#include <kstandarddirs.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <klistview.h>
#include <kdebug.h>
#include <kglobal.h>
#include <kconfig.h>
#include <ktoolbarbutton.h>
#include <kiconloader.h>
#include <ktextbrowser.h>

const QString ROOT_ELEM_NAME = "kkaddressdata-0.1";
const QString DOCUMENT_NAME = "kkaddressbook";

KKAddressBookDialog::KKAddressBookDialog( const QString &filename, QWidget *parent, const char *name )
	: KDialogBase( KDialogBase::Plain, i18n("AddressBook"), Ok|Cancel, Ok, parent, name )
	, m_filename( filename )
{
	setCaption( i18n( "KreetingKard Address Book" ) );

	contactDataList.setAutoDelete( true );
	contactDataList.clear();

	setupWidgets();

	readConfig();
	readData( m_filename );

	resize( configDialogSize( "KKAddressBookDialog" ) );
}

KKAddressBookDialog::~KKAddressBookDialog()
{
	writeConfig();
	saveData( m_filename );

	/* delete all allocated data */
	contactDataList.clear();

	saveDialogSize( "KKAddressBookDialog" );
}

void KKAddressBookDialog::setupWidgets()
{
	QFrame* page = plainPage();
        (new QHBoxLayout( page ))->setAutoAdd( true );

	mMainSplitter = new QSplitter( Horizontal, page );
	mMainSplitter->setOpaqueResize( true );

	/* Left Side */
	QVBox *leftVBox = new QVBox( mMainSplitter );
        leftVBox->setSpacing( 3 );

        QHBox *quickSearchHBox = new QHBox( leftVBox );
        quickSearchHBox->setSpacing( 6 );

        mContactListView = new KListView( leftVBox );
	mContactListView->addColumn( i18n("Name") );
        mContactListView->header()->hide();
	mContactListView->setFullWidth( true );
	mContactListView->setSortColumn( 0 );
	mContactListView->setAllColumnsShowFocus( true );
        mContactListView->setSelectionMode( QListView::Single );
        QObject::connect( mContactListView, SIGNAL( selectionChanged(QListViewItem *) ),
                          this, SLOT( slotSelectionChanged(QListViewItem *) ) );

        QToolButton *resetButton = new QToolButton( quickSearchHBox );
        resetButton->setIconSet( KGlobal::instance()->iconLoader()->loadIconSet( "locationbar_erase", KIcon::MainToolbar ) );
        QLabel *label = new QLabel( i18n("Search:"), quickSearchHBox );
        mQuickSearchLine = new KKContactQuickSearchLine( quickSearchHBox, mContactListView );
        label->setBuddy( mQuickSearchLine );
        QObject::connect( resetButton, SIGNAL( clicked() ),
                          mQuickSearchLine, SLOT( reset() ) );

        QWidget *leftButtons = new QWidget( leftVBox );

	newContactButton = new QToolButton( leftButtons );
	newContactButton->setText( i18n("Add") );
	newContactButton->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
	QToolTip::add( newContactButton, i18n("Add New Contact Data") );
	QObject::connect( newContactButton, SIGNAL( clicked() ),
			  this, SLOT( createNewContact() ) );

        modifyContactButton = new QToolButton( leftButtons );
        modifyContactButton->setText( i18n("Modify") );
        modifyContactButton->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
	QToolTip::add( modifyContactButton, i18n("Modify the data of selected item") );
        QObject::connect( modifyContactButton, SIGNAL( clicked() ),
                          this, SLOT( modifyContact() ) );

	removeContactButton = new QToolButton( leftButtons );
	removeContactButton->setText( i18n("Remove") );
	removeContactButton->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
	QToolTip::add( removeContactButton, i18n("Remove selected data") );
	QObject::connect( removeContactButton, SIGNAL( clicked() ),
			  this, SLOT( removeSelectedContactItem() ) );

        setGroupButton = new QToolButton( leftButtons );
        setGroupButton->setText( i18n("Setup Group") );
        removeContactButton->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
	QToolTip::add( setGroupButton, i18n("Setup Group list") );
        QObject::connect( setGroupButton, SIGNAL( clicked() ),
                          this, SLOT( setupGroup() ) );

        QHBoxLayout *leftButtonHLayout = new QHBoxLayout( leftButtons );
        leftButtonHLayout->setMargin( 1 );
        leftButtonHLayout->setSpacing( 6 );
        leftButtonHLayout->addWidget( newContactButton );
        leftButtonHLayout->addWidget( modifyContactButton );
        leftButtonHLayout->addWidget( removeContactButton );
//        leftButtonHLayout->addStretch();
        leftButtonHLayout->addSpacing( 10 );
        leftButtonHLayout->addWidget( setGroupButton );

	/* Right Side */
        mContactDataView = new KKContactDataView( mMainSplitter );

        setMainWidget( mMainSplitter );
}

/*
void KKAddressBookDialog::configureKeyBindings()
{
	KKeyDialog::configure( actionCollection(), this );
}

void KKAddressBookDialog::configureToolbars()
{
	saveMainWindowSettings( KGlobal::config(), "MainWindow" );

	KEditToolbar edit( factory() );
	connect( &edit, SIGNAL( newToolbarConfig() ),
		 this, SLOT( newToolbarConfig() ) );

	edit.exec();
}

void KKAddressBookDialog::newToolbarConfig()
{
	createGUI();
	applyMainWindowSettings( KGlobal::config(), "MainWindow" );
}
*/


void KKAddressBookDialog::createNewContact()
{
	KKNewContactDialog dlg( this );
	int result = dlg.exec();

	switch(result)
	{
	case KKNewContactDialog::AddNext:
	case KKNewContactDialog::OK:
		addContactData( dlg.getContactData() );
		saveData( m_filename );
		return;
	case KKNewContactDialog::Cancel:
		return;
	}

	if( result == KKNewContactDialog::AddNext )
		createNewContact(); // reopen KKNewContactDialog
}

void KKAddressBookDialog::modifyContact()
{
	const KKContactListViewItem *item = (KKContactListViewItem *)mContactListView->selectedItem();
	const KKContactData *d = NULL;
	if( item )
	{
		d = item->contactData();
	}
	else
	{
		return;
	}

	KKNewContactDialog dlg( this );
	if( d )
	{
		dlg.setContactData( *d );
	}

	int result = dlg.exec();
        switch (result) {
        case KKNewContactDialog::AddNext:
		removeContactData( d );
		removeSelectedContactItem();
		//--
		addContactData( dlg.getContactData() );
		createNewContact();
		break;
        case KKNewContactDialog::OK:
		removeContactData( d );
		removeSelectedContactItem();
		//--
		addContactData( dlg.getContactData() );
		break;
        case KKNewContactDialog::Cancel:
		return;
        }
}

void KKAddressBookDialog::removeSelectedContactItem()
{
	KKContactListViewItem *selectedItem = (KKContactListViewItem *)mContactListView->selectedItem();
	if( selectedItem )
	{
		// select proper item
		QListViewItem *nextItem = selectedItem->nextSibling();
		if( nextItem )
		{
			// select next item
			mContactListView->setSelected( nextItem, true );
		}
                else
		{
			// if no next item, select previous item
			QListViewItem *previousItem = selectedItem->itemAbove();
			if( previousItem )
				mContactListView->setSelected( previousItem, true );
			else
				mContactDataView->clearView(); // last data is removed
		}

		// remove
		const KKContactData *obsoleteData = selectedItem->contactData();
		removeContactData( obsoleteData );
		mContactListView->takeItem( selectedItem );
	}
}

void KKAddressBookDialog::addContactData( const KKContactData &d )
{
	kdDebug() << "KKAddressBookDialog::addContactData" << endl;

	KKContactData *storeData = new KKContactData(d);

	// add dada to the list
	contactDataList.append( storeData );

	// add item to the listview and show text
	KKContactListViewItem *item = new KKContactListViewItem( mContactListView, storeData );
	item->setText( 0, storeData->getFullname() );
	mContactListView->setSelected( item, true );

}

void KKAddressBookDialog::removeContactData( const KKContactData * obsoleteData )
{
	// delete data
	if( contactDataList.contains( obsoleteData ) )
	{
		contactDataList.remove( obsoleteData );
	}
}

void KKAddressBookDialog::setupGroup()
{
	KKSetupGroupDialog dlg( this );
	dlg.exec();

        if( dlg.isModified() )
            mQuickSearchLine->updateGroups();
}

bool KKAddressBookDialog::saveData( const QString &filename )
{
	kdDebug() << "KKAddressBookDialog::saveData()" << endl;	
	
	return ContactXML::instance().writeContactXML( filename, contactDataList );
}

void KKAddressBookDialog::readData( const QString &filename )
{
	kdDebug() << "KKAddressBookDialog::readData()" << endl;	

        /* delete old datas */
        if( !contactDataList.isEmpty() )
            contactDataList.clear();
         
	QPtrList<KKContactData> datas = ContactXML::instance().readContactXML( filename );
	for ( KKContactData *contactData = datas.first(); contactData; contactData = datas.next() )
	{
		// create new listviewitew
		KKContactListViewItem *item = new KKContactListViewItem( mContactListView, contactData );
		item->setText( 0, contactData->getFullname() );
	}

        /* Copying */
        contactDataList = datas;

	/* Choose First Item */
	QListViewItem *firstItem = mContactListView->firstChild();
	if( firstItem )
		mContactListView->setSelected( firstItem, true );
}

void KKAddressBookDialog::writeConfig()
{
	KConfig *conf = KGlobal::config();
	conf->setGroup( "KKAddressBook" );

	QString str;
	QTextOStream out( &str );
	out << *mMainSplitter;

	conf->writeEntry( "MainSplitter", str );
}

void KKAddressBookDialog::readConfig()
{
	KConfig *conf = KGlobal::config();
	conf->setGroup( "KKAddressBook" );

	QString str = conf->readEntry( "MainSplitter" );
	if( !str.isEmpty() )
	{
		QTextIStream in( &str );
		in >> *mMainSplitter;
	}
}

void KKAddressBookDialog::slotSelectionChanged( QListViewItem *i )
{
	const KKContactListViewItem *item = static_cast<const KKContactListViewItem*>( i );
	if( item )
	{
		const KKContactData *d = item->contactData();
		mContactDataView->setData( *d, "/home/kzk/kde-cvs/share/apps/kreetingkard/templates/Christmas_Blue.kk" );
	}
}

//----------------------------------------------------------------------
KKContactDataView::KKContactDataView( QWidget *parent, const char *name )
	: QWidget( parent, name )
{
	m_textbrowser = new KTextBrowser( this );
//	m_previewwidget = new KKView( this, true );

	QVBoxLayout *vLayout = new QVBoxLayout( this );
	vLayout->setSpacing( 6 );
	vLayout->addWidget( m_textbrowser );
//	vLayout->addWidget( m_previewwidget );
}

KKContactDataView::~KKContactDataView()
{

}

void KKContactDataView::setData( const KKContactData &data, const QString &templatefilename )
{
	QString str = QString::null;
	str.append( "<html><head></head><body><center>"
		    "<table>"
		    "<tr>"
		    "<td width=100>"+ i18n("Pronunciation") + "</td>"
		    "<td>" + data.getPronunciation() + "</td>"
		    "</tr>"
		    "<tr>"
		    "<td>" + i18n("FullName") + "</td>"
		    "<td>" + data.getFullname() + " " + data.getNameSuffix() + "</td>"
		    "</tr>"
		    "<tr>"
		    "<td>" + i18n("Group") + "</td>"
		    "<td>" + data.getGroup() + "</td>"
		    "</tr>"
		    "<tr>"
		    "<td>" + i18n("ZipCode") + "</td>"
		    "<td>" + data.getZipCode() + "</td>"
		    "</tr>"
		    "<tr>"
		    "<td>" + i18n("Address") + "</td>"
		    "<td>" + data.getAddress1() + data.getAddress2() + "</td>"
		    "</tr>");
	if( !data.getPCEmail().isEmpty() )
		str.append( "<tr>"
			    "<td>" + i18n("PC Email") + "</td>"
			    "<td>" + data.getPCEmail() + "</td>"
			    "</tr>" );
	if( !data.getPhoneNumber().isEmpty() )
		str.append( "<tr>"
			    "<td>" + i18n("Phone Number") + "</td>"
			    "<td>" + data.getPhoneNumber() + "</td>"
			    "</tr>" );
	if( !data.getCellularPhoneNumber().isEmpty() )
		str.append( "<tr>"
			    "<td>" + i18n("CellularPhone Number") + "</td>"
			    "<td>" + data.getCellularPhoneNumber() + "</td>"
			    "</tr>" );
	if( !data.getCellularPhoneEmail().isEmpty() )
		str.append( "<tr>"
			    "<td>" + i18n("CellularPhone Email") + "</td>"
			    "<td>" + data.getCellularPhoneEmail() + "</td>"
			    "</tr>" );
	str.append( "</table>"
		    "<center></body></html>");
	
	m_textbrowser->setText( str );
	/*
	if( !templatefilename.isEmpty() )
		m_previewwidget->preview( templatefilename );
	*/
}

void KKContactDataView::clearView()
{
	m_textbrowser->setText( "" );	
}
