/***************************************************************************
 *   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 "kknewcontactdialog.h"
#include "kkcontactdata.h"
#include "kkaddressbookglobalconfig.h"
#include "zipcode.h"

#include <qlabel.h>
#include <qlayout.h>
#include <qtoolbutton.h>
#include <qsizepolicy.h>
#include <qhbox.h>
#include <qtooltip.h>

#include <klocale.h>
#include <kglobal.h>
#include <kconfig.h>
#include <kmessagebox.h>
#include <klineedit.h>
#include <kcombobox.h>
#include <kseparator.h>
#include <kdebug.h>
#include <ktabwidget.h>

using namespace KKAddressBookPrivate;

#define ZIPCODE_LENGTH 7

QString KKNewContactDialog::lastSelectedGroup = QString::null;

KKNewContactDialog::KKNewContactDialog( QWidget *parent, const char *name )
	: KDialog( parent, name )
{
	setCaption( i18n("KreetingKard : Add New Contact") );

	init();

        resize( 400, 200 );
}

KKNewContactDialog::~KKNewContactDialog()
{

}

void KKNewContactDialog::init()
{
	checkZipCodeData();

	setupWidgets();

	// first focus
	mPronunciationEdit->setFocus();
}

void KKNewContactDialog::setupWidgets()
{
	QLabel *label;
	QGridLayout *layout;

	/* setup Upper side */
	QWidget *upperWidget = new QWidget( this );
	layout = new QGridLayout( upperWidget, 2, 4 );
	layout->setMargin( KDialog::marginHint() );
	layout->setSpacing( KDialog::spacingHint() );

	label = new QLabel( upperWidget );
	label->setText( i18n("Pronunciation") );
	mPronunciationEdit = new KLineEdit( upperWidget );
	label->setBuddy( mPronunciationEdit );
	layout->addWidget( label, 0, 1 );
	layout->addWidget( mPronunciationEdit, 0, 2 );

	label = new QLabel( upperWidget );
	label->setText( i18n("Name(*)") );
	mNameEdit = new KLineEdit( upperWidget );
	label->setBuddy( mNameEdit );
	layout->addWidget( label, 1, 1 );
	layout->addWidget( mNameEdit, 1, 2 );

	mNameSuffixCombo = new KComboBox( upperWidget );
	mNameSuffixCombo->insertItem( i18n("Sama") );
	mNameSuffixCombo->insertItem( i18n("Teacher") );
	layout->addWidget( mNameSuffixCombo, 1, 3 );

	mGroupCombo = new KComboBox( upperWidget );
	// insert groups
	QStringList groupList = KKAddressBookGlobalConfig::readGroupList();
	QStringList::ConstIterator it = groupList.begin();
	const QStringList::ConstIterator end = groupList.end();
	for( ; it != end; ++it )
	{
		mGroupCombo->insertItem( *it );		
	}
	// use cache
	if( !lastSelectedGroup.isEmpty() )
	{
		mGroupCombo->setCurrentText( lastSelectedGroup );		
	}
	layout->addWidget( mGroupCombo, 1, 4 );

	/* setup Lower side */
	mTabWidget  = new KTabWidget( this );
	mPageGeneral = setupPageGeneral();
	mPageDetail  = setupPageDetail();
	mTabWidget->addTab( mPageGeneral, i18n("General") );
	mTabWidget->addTab( mPageDetail, i18n("Detail") );

	/* Buttons */
	QHBox *hBox = new QHBox( this );
	hBox->setMargin( 6 );
	hBox->setSpacing( 6 );

	addNextButton = new QToolButton( hBox );
	addNextButton->setText( i18n("Add Next Contact") );
        addNextButton->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed );
	QToolTip::add( addNextButton, i18n("Add this contact and then add next new contact") );
	QObject::connect( addNextButton, SIGNAL( clicked() ),
			  this, SLOT( slotAddNext() ) );

	okButton = new QToolButton( hBox );
	okButton->setText( i18n("OK") );
        okButton->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed );
	QToolTip::add( okButton, i18n("Add this contact") );
	QObject::connect( okButton, SIGNAL( clicked() ),
			  this, SLOT( slotOK() ) );

	cancelButton = new QToolButton( hBox );
	cancelButton->setText( i18n("Cancel") );
        cancelButton->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed );
	QToolTip::add( cancelButton, i18n("Cancel this data") );
	QObject::connect( cancelButton, SIGNAL( clicked() ),
			  this, SLOT( slotCancel() ) );


	/* Main Layout */
	QVBoxLayout *mainLayout = new QVBoxLayout( this );
	mainLayout->setSpacing( 6 );
	mainLayout->addWidget( upperWidget );
	mainLayout->addWidget( new KSeparator( this ) );
	mainLayout->addWidget( mTabWidget );
	mainLayout->addWidget( new KSeparator( this ) );
	mainLayout->addWidget( hBox );
}

QWidget * KKNewContactDialog::setupPageGeneral()
{
	QLabel *label;
       	
	QWidget *pageGeneral = new QWidget( this );
	QGridLayout *layout = new QGridLayout( pageGeneral, 5, 4 );
	layout->setMargin( KDialog::marginHint() );
	layout->setSpacing( KDialog::spacingHint() );

	label = new QLabel( pageGeneral );
	label->setText( i18n("ZipCode") );
        
	QHBox *zipcodeHBox = new QHBox( pageGeneral );
	zipcodeHBox->setSpacing( 6 );
	
	mZipCodeEdit = new KLineEdit( zipcodeHBox );
	mZipCodeEdit->setInputMask( "999-9999" );
	label->setBuddy( mZipCodeEdit );
	QObject::connect( mZipCodeEdit, SIGNAL( returnPressed() ),
			  this, SLOT( slotZipCodeSearch() ) );
	mSearchButton = new QToolButton( zipcodeHBox );
	mSearchButton->setText( i18n("Search") );
	QToolTip::add( mSearchButton, i18n("Search address from ZipCode") );
	QObject::connect( mSearchButton, SIGNAL( clicked() ),
			  this, SLOT( slotZipCodeSearch() ) );

        layout->addWidget( label, 0, 1 );
	layout->addWidget( zipcodeHBox, 0, 2 );
	
	label = new QLabel( pageGeneral );
	label->setText( i18n("Address1(*)") );
	mAddress1Edit = new KLineEdit( pageGeneral );
	label->setBuddy( mAddress1Edit );
	layout->addWidget( label, 1, 1 );
	layout->addWidget( mAddress1Edit, 1, 2 );

	label = new QLabel( pageGeneral );
	label->setText( i18n("Address2") );
	mAddress2Edit = new KLineEdit( pageGeneral );
	label->setBuddy( mAddress2Edit );
	layout->addWidget( label, 2, 1 );
	layout->addWidget( mAddress2Edit, 2, 2 );

	return pageGeneral;
}

QWidget * KKNewContactDialog::setupPageDetail()
{
	QLabel *label;
	
	QWidget *pageDetail = new QWidget( this );
	QGridLayout *layout = new QGridLayout( pageDetail, 3, 4 );
	layout->setMargin( KDialog::marginHint() );
	layout->setSpacing( KDialog::spacingHint() );

	label = new QLabel( pageDetail );
	label->setText( i18n("PC Email") );
	mPCEmailEdit = new KLineEdit( pageDetail );
	label->setBuddy( mPCEmailEdit );
	layout->addWidget( label, 0, 1 );
	layout->addWidget( mPCEmailEdit, 0, 2 );

        label = new QLabel( pageDetail );
	label->setText( i18n("Phone Number") );
	mPhoneNumberEdit = new KLineEdit( pageDetail );
	label->setBuddy( mPhoneNumberEdit );
	layout->addWidget( label, 1, 1 );
	layout->addWidget( mPhoneNumberEdit, 1, 2 );

	label = new QLabel( pageDetail );
	label->setText( i18n("Cellular Phone Number") );
	mCellularPhoneNumberEdit = new KLineEdit( pageDetail );
	label->setBuddy( mCellularPhoneNumberEdit );
	layout->addWidget( label, 3, 1 );
	layout->addWidget( mCellularPhoneNumberEdit, 3, 2 );

	label = new QLabel( pageDetail );
	label->setText( i18n("Cellular Phone Email") );
	mCellularPhoneEmailEdit = new KLineEdit( pageDetail );
	label->setBuddy( mCellularPhoneEmailEdit );
	layout->addWidget( label, 4, 1 );
	layout->addWidget( mCellularPhoneEmailEdit, 4, 2 );

        return pageDetail;
}


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

	// check if ZipCode is available
	bool isDownloadZipCode = conf->readBoolEntry( "isDownloadZipCode", false );
	if( isDownloadZipCode == false )
	{
		KMessageBox::information( this, i18n("This is the first time to add contact."
						     "Now KreetingKard starts downloadding the ZipCode data.") );

		// download
		bool isSuccess = ZipCode::instance().update( this );
		conf->writeEntry( "isDownloadZipCode", isSuccess );
	}
}

void KKNewContactDialog::slotZipCodeSearch()
{
	QString zipCode = mZipCodeEdit->text();
	zipCode.remove( '-' );

	// check if str is valid for zipcode
	bool ok;
	zipCode.toDouble( &ok );
	if( ok && zipCode.length() == ZIPCODE_LENGTH )
	{
		// 2004-11-11 Kazuki Ohta <mover@hct.zaq.ne.jp>
		// Too Slow
		mAddress1Edit->setText( ZipCode::instance().lookup( zipCode ) );
		mAddress1Edit->setFocus();
	}
}

bool KKNewContactDialog::isValidData()
{
	bool isNameEmpty = mNameEdit->text().isEmpty();
	bool isAddressEmpty = (mAddress1Edit->text().isEmpty() && mAddress2Edit->text().isEmpty());
	if( isNameEmpty
	    || isAddressEmpty )
	{
		KMessageBox::error( this, i18n("Data should at least contain Name and Address data") );

		// Set focus for valid place
		if( isNameEmpty )
		{
			mNameEdit->setFocus();
		}
		else
		{
			mTabWidget->setCurrentPage( mTabWidget->indexOf( mPageGeneral ) );
			mAddress1Edit->setFocus();
		}
		
		return false;
	}
	else
	{
		return true;		
	}
}

void KKNewContactDialog::slotAddNext()
{
	if( isValidData() )
		done( KKNewContactDialog::AddNext );
}

void KKNewContactDialog::slotOK()
{
	if( isValidData() )
		done( KKNewContactDialog::OK );
}

void KKNewContactDialog::slotCancel()
{
	done( KKNewContactDialog::Cancel );
}

KKContactData KKNewContactDialog::getContactData()
{
	// for cache
	lastSelectedGroup = mGroupCombo->currentText();
	
	return KKContactData( mPronunciationEdit->text(),
			      mNameEdit->text(),
			      mNameSuffixCombo->currentText(),
			      mGroupCombo->currentText(),
			      mZipCodeEdit->text(),
			      mAddress1Edit->text(),
			      mAddress2Edit->text(),
			      mPCEmailEdit->text(),
			      mPhoneNumberEdit->text(),
			      mCellularPhoneNumberEdit->text(),
			      mCellularPhoneEmailEdit->text() );
}

void KKNewContactDialog::setContactData( const KKContactData & d )
{
	mPronunciationEdit->setText( d.getPronunciation() );
	mNameEdit->setText( d.getFullname() );
	mNameSuffixCombo->setCurrentText( d.getNameSuffix() );
	mGroupCombo->setCurrentText( d.getGroup() );
	mZipCodeEdit->setText( d.getZipCode() );
	mAddress1Edit->setText( d.getAddress1() );
	mAddress2Edit->setText( d.getAddress2() );
	mPCEmailEdit->setText( d.getPCEmail() );
	mPhoneNumberEdit->setText( d.getPhoneNumber() );
	mCellularPhoneNumberEdit->setText( d.getCellularPhoneNumber() );
	mCellularPhoneEmailEdit->setText( d.getCellularPhoneEmail() );
}
