/***************************************************************************
 *   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 "kkacontactxml.h"
#include "kkatreeview.h"
#include "kkacontactdata.h"
#include "kkahomeaddress.h"
#include "kkaofficeaddress.h"
#include "kkagroup.h"

#include <qregexp.h>
#include <qfileinfo.h>

#include <kfiledialog.h>
#include <klocale.h>
#include <kdebug.h>
#include <kmessagebox.h>
#include <kiconloader.h>

using namespace KKAddressBook;

void KKAContactXML::doImport( KKATreeView* tvw )
{
	QString filename = KFileDialog::getOpenFileName( ":<KreetingKard_ContactXML>", i18n( "*.xml|ContactXML File (*.xml)\n*.*|All File (*.*)" ), tvw );
	if( filename.isEmpty() ) return;

	QFile file( filename );
	if( !file.open( IO_ReadOnly ) )
	{
		KMessageBox::error( tvw, i18n( "File open error\n%1" ).arg( filename ) );
		return;
	}

	QDomDocument doc( "ContactXML" );
	if( !doc.setContent( &file ) )
	{
		KMessageBox::error( tvw, i18n( "File is not ContactXML format" ) );
		return;
	}
	file.close();

	QFileInfo info( filename );
	KKAGroup* group = 0;
	int i = 0;
	bool bl = false;
	while( !bl )
	{
		bl = true;
		for( QListViewItem* item = tvw->firstChild(); item; item = item->nextSibling() )
		{
			if( item->text( 0 ) == info.baseName() + ( i == 0 ? QString( "" ) : QString::number( i ) ) )
			{
				bl = false;
				break;
			}
		}
		if( !bl ) i++;
	}
	group = new KKAGroup( tvw );
	group->setText( 0, info.baseName() + ( i == 0 ? QString( "" ) : QString::number( i ) ) );
	
	for( QDomNode n = doc.documentElement().lastChild(); !n.isNull(); n = n.previousSibling() )
	{
		QDomElement elem = n.toElement();
		if( elem.tagName() == "ContactXMLItem" )
		{
			KKAContactData* data = new KKAContactData( tvw );
			parseItem( elem, data );
			group->addImportData( data );
		}
	}
	tvw->setCurrentItem( group );
}

void KKAContactXML::parseItem( QDomElement& elem, KKAContactData* data )
{
	for( QDomNode n = elem.lastChild(); !n.isNull(); n = n.previousSibling() )
	{
		QDomElement e = n.toElement();
		if( e.tagName() == "PersonName" )
		{
			for( QDomNode nPerson = e.firstChild(); !nPerson.isNull(); nPerson = nPerson.nextSibling() )
			{
				QDomElement ePerson = nPerson.toElement();
				if( ePerson.tagName() == "PersonNameItem" )
				{
					parsePerson( ePerson, data );
				}
			}
		}
		else if( e.tagName() == "Address" )
		{
			for( QDomNode nAddress = e.firstChild(); !nAddress.isNull(); nAddress = nAddress.nextSibling() )
			{
				QDomElement eAddress = nAddress.toElement();
				if( eAddress.tagName() == "AddressItem" )
				{
					parseAddress( eAddress, data );
				}
			}
		}
		else if( e.tagName() == "Occupation" )
		{
			for( QDomNode nOccupation = e.firstChild(); !nOccupation.isNull(); nOccupation = nOccupation.nextSibling() )
			{
				QDomElement eOccupation = nOccupation.toElement();
				if( eOccupation.tagName() == "OccupationItem" )
				{
					parseOccupation( eOccupation, data );
				}
			}
		}
		else if( e.tagName() == "Extension" )
		{
			for( QDomNode nExtension = e.firstChild(); !nExtension.isNull(); nExtension = nExtension.nextSibling() )
			{
				QDomElement eExtension = nExtension.toElement();
				if( eExtension.tagName() == "ExtensionItem" )
				{
					parseExtension( eExtension, data );
				}
			}
		}
	}
}

void KKAContactXML::parsePerson( QDomElement& elem, KKAContactData* data )
{
	QString full;
	QStringList each;
	each << QString::null << QString::null << QString::null;
	for( QDomNode n = elem.lastChild(); !n.isNull(); n = n.previousSibling() )
	{
		QDomElement e = n.toElement();
		if( e.tagName() == "FullName" )
		{
			full = e.text();
		}
		else if( e.tagName() == "FirstName" )
		{
			each[2] = e.text();
		}
		else if( e.tagName() == "MiddleName" )
		{
			each[1] = e.text();
		}
		else if( e.tagName() == "LastName" )
		{
			each[0] = e.text();
		}
	}
	each.remove( QString::null );
	if( each.count() > 0 )
	{
		data->setName( each.join( " " ) );
	}
	else
	{
		data->setName( full );
	}
}

void KKAContactXML::parseAddress( QDomElement& elem, KKAContactData* data )
{
	KKAAddressData* address;
	QString str = elem.attribute( "locationType" );
	if( str == "Home" )
	{
		address = data->home();
	}
	else if( str == "Office" )
	{
		address = data->office();
	}
	else
	{
		return;
	}
	
	if( elem.hasAttribute( "preference" ) )
	{
		address->setPreference( elem.attribute( "preference" ) == "True" );
	}
	
	QString full;
	QStringList each;
	each << QString::null << QString::null << QString::null << QString::null << QString::null << QString::null;
	QString country = KGlobal::locale()->country();
	for( QDomNode n = elem.lastChild(); !n.isNull(); n = n.previousSibling() )
	{
		QDomElement e = n.toElement();
		if( e.tagName() == "AddressCode" )
		{
			QString domain = e.attribute( "codeDomain" );
			if( domain == "ZIP7" )
			{
				QString zipcode = e.text();
				if( zipcode.length() == 7 )
				{
					zipcode.insert( 3, "-" );
					address->setZipcode( zipcode );
				}
			}
			else if( domain == "Country" )
			{
				country = e.text().lower();
			}
		}
		else if( e.tagName() == "FullAddress" )
		{
			full = e.text();
		}
		else if( e.tagName() == "AddressLine" )
		{
			int level = -1;
			QString type = e.attribute( "addressLineType" );
			if( type == "Country" ){ level = 0; }
			else if( type == "Prefecture" ){ level = 1; }
			else if( type == "City" ){ level = 2; }
			else if( type == "Town" ){ level = 3; }
			else if( type == "Number" ){ level = 4; }
			else if( type == "Building" ){ level = 5; }
			if( level != -1 )
			{
				each[level] = e.text();
			}
		}
	}
	address->setCountry( country );
	each.remove( QString::null );
	if( each.count() > 0 )
	{
		address->setAddress( each.join( " " ) );
	}
	else
	{
		address->setAddress( full );
	}
}

void KKAContactXML::parseOccupation( QDomElement& elem, KKAContactData* data )
{
	for( QDomNode n = elem.lastChild(); !n.isNull(); n = n.previousSibling() )
	{
		QDomElement e = n.toElement();
		if( e.tagName() == "OrganizationName" )
		{
			data->office()->setCorporation( e.text() );
		}
		else if( e.tagName() == "Department" )
		{
			data->office()->setSection( e.text() );
		}
		else if( e.tagName() == "JobTitle" )
		{
			data->office()->setPost( e.text() );
		}
	}
}

void KKAContactXML::parseExtension( QDomElement& elem, KKAContactData* data )
{
	QString type = elem.attribute( "extensionType" );
	QString name = elem.attribute( "name" );
	if( type == "Common" )
	{
		if( name == "Suffix" )
		{
			data->setSuffix( elem.text() );
		}
		else if( name == "NamesOfFamily" )
		{
			for( uint i = 0; i != KKAHomeAddress::JointNameCount; i++ )
			{
				KKAPersonalData* d = data->home()->at( i );
				if( !d->isValid() )
				{
					d->setName( elem.text() );
					break;
				}
			}
		}
	}
	else
	{
		QRegExp rx( "^Term(\\d+)$" );
		if( rx.search( name ) > -1 )
		{
			int idx = rx.cap(1).toInt() - 1;
			if( idx < KKAHomeAddress::JointNameCount )
			{
				data->home()->at( idx )->setSuffix( elem.text() );
			}
		}
	}
}

void KKAContactXML::doExport( KKATreeView* tvw )
{
	KURL url = KFileDialog::getSaveFileName( ":<KreetingKard_ContactXML>", i18n( "*.xml|ContactXML File (*.xml)\n*.*|All File (*.*)" ), tvw );
	if( url.isEmpty() ) return;
	if( !url.isLocalFile() )
	{
		KMessageBox::sorry( tvw, i18n( "KreetingKard cannot handle remote files yet") );
		return;
	}
	if( QFile::exists( url.path() ) )
	{
		if( KMessageBox::questionYesNo( tvw, i18n( "A file named \"%1\" already exists. Are you sure you want to overwrite it?" ).arg( url.fileName() ), i18n( "Overwrite File?" ), KGuiItem( i18n( "Overwrite" ), SmallIcon( "filesave" ) ) ) == KMessageBox::No )
		{
			return;
		}
	}
}
