/***************************************************************************
 *   Copyright (C) 2005 by SUZUKI Tasuku                                   *
 *   tasuku@linux-life.net                                                 *
 *                                                                         *
 *   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 "kkaaddresswidget.h"
#include "kkaaddressdata.h"
#include "kkaaddressmanager.h"
#include "kkazipcodeedit.h"

#include <qlabel.h>
#include <qhbox.h>
#include <klanguagebutton.h>
#include <klineedit.h>
#include <ktextedit.h>
#include <klocale.h>
#include <kglobal.h>
#include <kstandarddirs.h>
#include <ksimpleconfig.h>
#include <qpixmap.h>
#include <qiconset.h>
#include <kdebug.h>
#include <qtoolbutton.h>
#include <kiconloader.h>
#include <kapplication.h>
#include <kmessagebox.h>

using namespace KKAddressBook;

KKAAddressWidget::KKAAddressWidget(QWidget *parent, const char *name)
 : QGrid( 2, parent, name )
 , m_data( NULL )
{
	setupWidgets();
}

KKAAddressWidget::~KKAAddressWidget()
{
}

void KKAAddressWidget::setupWidgets()
{
	QHBox* hbox;

	new QLabel( i18n( "Country" ), this );
	hbox = new QHBox( this );
	m_country = new KLanguageButton( hbox );
	loadCountry();
	new QLabel( hbox );
	m_setup = new QToolButton( hbox );
	m_setup->setPixmap( BarIcon( "configure" ) );
	m_setup->setSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed );

	new QLabel( i18n( "Zipcode" ), this );
	hbox = new QHBox( this );
	m_zipcode = new KKAZipcodeEdit( hbox );
	m_zipcode2address = new QToolButton( hbox );
	m_zipcode2address->setPixmap( BarIcon( "find" ) );
	m_zipcode2address->setSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed );
// 	new QLabel( hbox );

	(new QLabel( i18n( "Address" ), this ))->setAlignment( AlignTop );
	m_address = new KTextEdit( this );

	connect( m_country, SIGNAL( activated( const QString& ) ), this, SIGNAL( countryChanged( const QString& ) ) );
	connect( m_country, SIGNAL( activated( const QString& ) ), this, SLOT( setup( const QString& ) ) );
	connect( m_country, SIGNAL( activated( const QString& ) ), m_zipcode, SLOT( setCountry( const QString& ) ) );
	connect( m_zipcode, SIGNAL( textChanged( const QString& ) ), this, SIGNAL( zipcodeChanged( const QString& ) ) );
	connect( m_zipcode, SIGNAL( returnPressed( const QString& ) ), this, SLOT( zipcode2address() ) );
	connect( m_zipcode2address, SIGNAL( clicked() ), this, SLOT( zipcode2address() ) );
	connect( m_address, SIGNAL( textChanged() ), this, SLOT( setAddress() ) );
	connect( m_setup, SIGNAL( clicked() ), this, SLOT( setup() ) );
}

/**
 * @see http://websvn.kde.org/branches/KDE/3.4/kdebase/kpersonalizer/kcountrypage.cpp?rev=409205&view=auto
 */
void KKAAddressWidget::loadCountry()
{
	QString sub = QString::fromLatin1("l10n/");

	QStringList regionfiles = KGlobal::dirs()->findAllResources("locale", sub + "*.desktop");
	QMap<QString,QString> regionnames;

	for ( QStringList::ConstIterator it = regionfiles.begin(); it != regionfiles.end(); ++it )
	{
			KSimpleConfig entry(*it);
			entry.setGroup(QString::fromLatin1("KCM Locale"));
			QString name = entry.readEntry(QString::fromLatin1("Name"), i18n("without name"));

			QString tag = *it;
			int index;

			index = tag.findRev('/');
			if (index != -1)
					tag = tag.mid(index + 1);

			index = tag.findRev('.');
			if (index != -1)
					tag.truncate(index);

			regionnames.insert(name, tag);
	}

	for ( QMap<QString,QString>::ConstIterator mit = regionnames.begin(); mit != regionnames.end(); ++mit )
	{
			m_country->insertSubmenu( mit.key(), '-' + mit.data(), sub );
	}

	// add all languages to the list
	QStringList countrylist = KGlobal::dirs()->findAllResources("locale", sub + "*/entry.desktop");
	countrylist.sort();

	for ( QStringList::ConstIterator it = countrylist.begin(); it != countrylist.end(); ++it ) {
			KSimpleConfig entry(*it);
			entry.setGroup(QString::fromLatin1("KCM Locale"));
			QString name = entry.readEntry(QString::fromLatin1("Name"), i18n("without name"));
			QString submenu = '-' + entry.readEntry("Region");

			QString tag = *it;
			int index = tag.findRev('/');
			tag.truncate(index);
			index = tag.findRev('/');
			tag = tag.mid(index+1);

			QPixmap flag( locate( "locale", QString::fromLatin1("l10n/%1/flag.png").arg(tag) ) );
			QIconSet icon( flag );
			m_country->insertItem( icon, name, tag, submenu );
	}
}

void KKAAddressWidget::setData( KKAAddressData* data )
{
	if( m_data == data ) return;
	if( m_data )
	{
		disconnect( m_country, SIGNAL( activated( const QString& ) ), m_data, SLOT( setCountry( const QString& ) ) );
		disconnect( m_zipcode, SIGNAL( textChanged( const QString& ) ), m_data, SLOT( setZipcode( const QString& ) ) );
	}
	m_data = data;
	if( m_data )
	{
		m_country->setCurrentItem( m_data->country() );
		setup( m_data->country() );
		m_zipcode->setText( m_data->zipcode() );
		m_zipcode->setCountry( m_country->current() );
		m_address->setText( m_data->address() );
		connect( m_country, SIGNAL( activated( const QString& ) ), m_data, SLOT( setCountry( const QString& ) ) );
		connect( m_zipcode, SIGNAL( textChanged( const QString& ) ), m_data, SLOT( setZipcode( const QString& ) ) );
	}
	else
	{
		m_country->setCurrentItem( "C" );
		setup( "C" );
		m_zipcode->setText( "" );
		m_address->setText( "" );
	}
}

void KKAAddressWidget::setAddress()
{
	if( !m_data ) return;
	m_data->setAddress( m_address->text() );
	emit addressChanged( m_address->text() );
}

void KKAAddressWidget::setup()
{
	bool ok = KKAAddressManager::manager( m_country->current() )->setup( this );
	if( ok ) setup( m_country->current() );
}

void KKAAddressWidget::setup( const QString& country )
{
	KKAAddressManager* manager = KKAAddressManager::manager( country );
	if( m_zipcode->inputMask() != manager->mask() )
	{
		m_zipcode->setInputMask( manager->mask() );
	}
	m_zipcode2address->setEnabled( manager->available() );
}

void KKAAddressWidget::zipcode2address()
{
	if( !m_zipcode2address->isEnabled() ) return;
	KApplication::setOverrideCursor( Qt::waitCursor );
	QString str = KKAAddressManager::manager( m_country->current() )->zipcode2address( m_zipcode->text() );
	KApplication::restoreOverrideCursor();
	if( !str.isNull() )
	{
		m_address->setText( str );
		m_address->setFocus();
	}
}

QString KKAAddressWidget::country() const
{
	return m_country->current();
}
