/***************************************************************************
                          addressbookthread.cpp  -  description
                             -------------------
    begin                : Sat Feb 14 2003
    copyright            : (C) 2003 by Simone Gotti
    email                : simone.gotti@email.it
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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.                                   *
 *                                                                         *
 ***************************************************************************/

#include <kdebug.h>
#include <klocale.h>

#include <qregexp.h>
#include <qfile.h>
#include <qdir.h>

#include <kabc/vcardconverter.h>

#include <idhelper.h>

#include "addressbookthread.h"
#include "device.h"


using namespace KSync;
using namespace KABC;

/**
   Constructor.
*/
AddressBookThread::AddressBookThread(const IrMCSyncHelper::Device::Model phoneModel, QObject* reciver )
		: IrMCSyncThreadBase("addressbook", "pb", "vcf", phoneModel, reciver )
{
	mSyncee = new AddressBookSyncee();
	mSyncee->setTitle( i18n( "IrMCSync" ) );
  mSyncee->setMerger( mDeviceHelper->merger( IrMCSyncHelper::Device::Addressbook ) );
	// FIXME
	// We have to set this Here and not in the functions or we'll get a DCOP Error! 
	// This only with the threads, so I think it's a thread problem
	//rawDatatoSynceeSyncee = new AddressBookSyncee();
	//localGetEntrySyncee = new AddressBookSyncee();

	kdDebug(0) << "TITLE: " << mSyncee->title() << endl;

}

/**
   Destructor./
*/
AddressBookThread::~AddressBookThread()
{}

void AddressBookThread::clearSyncee(Syncee* syncee)
{
	//We have to remove all the entries from the syncee
	/*KSync::SyncEntry *entry;
	//while((entry = syncee->firstEntry())) {
	/*for ( entry = syncee->firstEntry(); entry != 0; entry = syncee->nextEntry() ) {
		syncee->removeEntry(entry);
	}*/

}

KSync::Syncee* AddressBookThread::rawDataToSyncee(QByteArray data, QStringList& XIRMCLUIDs)
{
	kdDebug() << "rawDataToSyncee()" << endl;
	
	rawDatatoSynceeSyncee = new AddressBookSyncee();
	//clearSyncee(rawDatatoSynceeSyncee);
	
	// Get the X-IRMC-LUID
	QStringList fullCalendarStrings;
	
	QTextStream changelogStream(data, IO_ReadOnly);
	QString tmp;
	while ((tmp = changelogStream.readLine()) != QString::null)
		fullCalendarStrings.append(tmp);

	kdDebug() << "Getting X-IRMC-LUIDs" << endl;
	QRegExp rxp("^X-IRMC-LUID:");
	QStringList matchingStrings = fullCalendarStrings.grep(rxp);
	QStringList::Iterator matchingStringsIt;
	for ( matchingStringsIt = matchingStrings.begin(); matchingStringsIt != matchingStrings.end(); ++matchingStringsIt )
		XIRMCLUIDs.append((*matchingStringsIt).section(rxp, 1));

	// Convert the QByteArray in the Vcal format
	QString dataString(data);
	kdDebug() << dataString << endl;

	VCardConverter converter;
	kdDebug() << "Converting VCards" << endl;
	Addressee::List addresseeList = converter.parseVCards( dataString );

	Addressee::List::Iterator it;
	kdDebug() << "There are " << addresseeList.size() << " addresses" << endl;

	QString LUID, Uid, dstFileName;
	QStringList::Iterator XIRMCLUIDsIt = XIRMCLUIDs.begin();
	for ( it = addresseeList.begin(); it != addresseeList.end(); ++it ) {
				// Get the associated LUID
		if(XIRMCLUIDsIt == XIRMCLUIDs.end()) {
			kdDebug() << "Error: More Events then LUIDs!!!" << endl;
		}
		//Save the entry in the serialnumber/database dir.
		QString LUID, Uid, dstFileName;
		LUID = (*XIRMCLUIDsIt);

		//		 (*it).setResource( mAddressBook->resources().first() );
		// THIS IS A WORKAROUND!!!!!!!!		BEGIN
		// We check if there's a local file with the same LUID
		// We have to do this because we have to know the real Uid of the entry
		// In fact when we import it with vcal o VCardConverter a new Uid is assigned
		// every time, but if the entry already exists we have to get the real Uid
		Uid = uidHelper->kdeId(appName, LUID);
		dstFileName = GenerateFullPathFileName(LUID);
		if(QFile::exists(dstFileName)) {
			// We have to set the Uid to the local Uid and NOT the device LUID!!!
			(*it).setUid(Uid);
		} else {
			// If there's no an existing entry we can choose like local Uid
			// the same value of the "IrMCSyncKonnector-" + LUID
			Uid = "IrMCSyncKonnector-" + LUID;
			(*it).setUid(Uid);
			uidHelper->addId(appName, LUID, Uid);
			uidHelper->save();
		}
		KSync::AddressBookSyncEntry* entry = new KSync::AddressBookSyncEntry(*it, mSyncee);
		rawDatatoSynceeSyncee->addEntry(entry);

		XIRMCLUIDsIt++;
	}
	return rawDatatoSynceeSyncee;
}

QByteArray AddressBookThread::syncEntryToRawData(KSync::SyncEntry* entry, QString& Uid)
{
	kdDebug() << "syncEntryToRawData()" << endl;
	Addressee curAddressee;
	curAddressee = (Addressee)((KSync::AddressBookSyncEntry*)entry)->addressee();

	Uid = curAddressee.uid();

	VCardConverter converter;
	QString vcard = converter.createVCard( curAddressee, VCardConverter::v2_1);

	QCString tmp(vcard.latin1());
	QByteArray data(tmp);

	return data;
}

KSync::Syncee* AddressBookThread::localGetEntry(const QString& path)
{
	kdDebug() << "localGetEntry()" << endl;
	
	//We have to remove all the entries from the syncee
	//clearSyncee(localGetEntrySyncee);
	localGetEntrySyncee = new AddressBookSyncee();
	
	QByteArray data;
	QFile file(path);
	file.open(IO_ReadOnly);
	data = file.readAll();
	file.close();

	QString dataString(data);

	VCardConverter converter;
	Addressee::List addresseeList = converter.parseVCards( dataString );

	Addressee::List::Iterator it;
	kdDebug() << "There are " << addresseeList.size() << " addresses" << endl;

	for ( it = addresseeList.begin(); it != addresseeList.end(); ++it ) {
		KSync::AddressBookSyncEntry* entry = new KSync::AddressBookSyncEntry(*it, mSyncee);
		localGetEntrySyncee->addEntry(entry);
	}
	return localGetEntrySyncee;
}

void AddressBookThread::localPutEntry(KSync::SyncEntry* entry, const QString& path)
{
	kdDebug() << "localPutEntry()" << endl;
	Addressee curAddresee;
	kdDebug() << "curAddresee = (Addressee)((KSync::AddressBookSyncEntry*)entry)->addressee();" << endl;
	curAddresee = (Addressee)((KSync::AddressBookSyncEntry*)entry)->addressee();
	
	VCardConverter converter;
	kdDebug() << "QString vcard = converter.createVCard( curAddresee, VCardConverter::v2_1);" << endl;
	QString vcard = converter.createVCard( curAddresee );
	
	QCString tmp(vcard.latin1());
	QByteArray data(tmp);
	kdDebug() << vcard << endl;
	QFile file(path);
	file.open(IO_WriteOnly);
	kdDebug() << "file.writeBlock(data);" << endl;
	file.writeBlock(data);
	file.close();
}


#include "addressbookthread.moc"
