/*
    globalidentitiesmanager.h  -  Kopete Global identities manager.

    Copyright (c) 2005      by Michaël Larouche       <michael.larouche@kdemail.net>

    Kopete    (c) 2003-2005 by the Kopete developers  <kopete-devel@kde.org>

    *************************************************************************
    *                                                                       *
    * 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 "globalidentitiesmanager.h"

// TQt includes
#include <tqdom.h>
#include <tqfile.h>
#include <tqtextstream.h>

// KDE includes
#include <kdebug.h>
#include <ksavefile.h>
#include <tdelocale.h>
#include <kurl.h>
#include <kstandarddirs.h>

// Kopete includes
#include "kopetecontact.h"
#include "kopetemetacontact.h"
#include "kopetecontactlist.h"
#include "kopetepluginmanager.h"

class GlobalIdentitiesManager::Private
{
public:
	TQMap<TQString, Kopete::MetaContact*> identitiesList;
};

GlobalIdentitiesManager *GlobalIdentitiesManager::s_self = 0L;
GlobalIdentitiesManager *GlobalIdentitiesManager::self()
{
	if ( !s_self )
		s_self = new GlobalIdentitiesManager;

	return s_self;
}

GlobalIdentitiesManager::GlobalIdentitiesManager(TQObject *parent, const char *name)
        : TQObject(parent, name)
{
	d = new Private;
}

GlobalIdentitiesManager::~GlobalIdentitiesManager()
{
	s_self = 0L;

	delete d;
}

void GlobalIdentitiesManager::createNewIdentity(const TQString &identityName)
{
	// Create new identity metacontact based on myself to get the sub-contacts.
	Kopete::MetaContact *newIdentity = createNewMetaContact();
	
	// Add to internal list.
	d->identitiesList.insert(identityName, newIdentity);
}

void GlobalIdentitiesManager::copyIdentity(const TQString &copyIdentityName, const TQString &sourceIdentity)
{
	Kopete::MetaContact *copyIdentity = createCopyMetaContact(d->identitiesList[sourceIdentity]);
	
	d->identitiesList.insert(copyIdentityName, copyIdentity);
}

void GlobalIdentitiesManager::renameIdentity(const TQString &oldName, const TQString &newName)
{
	Kopete::MetaContact *renamedIdentity = d->identitiesList[oldName];
	d->identitiesList.remove(oldName);
	d->identitiesList.insert(newName, renamedIdentity);
}

void GlobalIdentitiesManager::removeIdentity(const TQString &removedIdentity)
{
	// Clear from memory the identity metacontact.
	delete d->identitiesList[removedIdentity];
	// Remove from the list.
	d->identitiesList.remove(removedIdentity);
}

void GlobalIdentitiesManager::updateIdentity(const TQString &updatedIdentity, Kopete::MetaContact *sourceMetaContact)
{
	copyMetaContact(d->identitiesList[updatedIdentity], sourceMetaContact);
}

bool GlobalIdentitiesManager::isIdentityPresent(const TQString &identityName)
{
	TQMapIterator<TQString, Kopete::MetaContact*> it;
	TQMapIterator<TQString, Kopete::MetaContact*> end = d->identitiesList.end();

	for(it = d->identitiesList.begin(); it != end; ++it)
	{
		if(it.key() == identityName)
		{
			// A entry with the same name was found.
			return true;
		}
	}
	return false;
}

Kopete::MetaContact *GlobalIdentitiesManager::getIdentity(const TQString &identityName)
{
	// Check if the identity is present.
	return isIdentityPresent(identityName) ? d->identitiesList[identityName] : 0;
}

void GlobalIdentitiesManager::loadXML()
{
	kdDebug() << k_funcinfo << "Loading global identities list from XML." << endl;

	TQString filename = locateLocal( "appdata", TQString::fromUtf8("global-identities.xml") );
	if( filename.isEmpty() )
	{
		return;
	}

	TQDomDocument globalIdentitiesList( TQString::fromUtf8( "kopete-global-identities-list" ) );
	
	TQFile globalIdentitiesListFile( filename );
	globalIdentitiesListFile.open( IO_ReadOnly );
	globalIdentitiesList.setContent( &globalIdentitiesListFile );

	TQDomElement list = globalIdentitiesList.documentElement();
	TQDomElement element = list.firstChild().toElement();
	while( !element.isNull() )
	{
		if( element.tagName() == TQString::fromUtf8("identity") )
		{
			Kopete::MetaContact *metaContact = createNewMetaContact();
			TQString identityName = element.attribute(TQString::fromUtf8("name"));

			if(!metaContact->fromXML(element))
			{
				delete metaContact;
				metaContact = 0L;
			}
			else
			{
				d->identitiesList.insert(identityName, metaContact);
			}
		}
		element = element.nextSibling().toElement();
	}

	// If no identity are loaded, create a default identity MetaContact.
	if(d->identitiesList.empty())
	{
		createNewIdentity(i18n("Default Identity"));
	}
}

void GlobalIdentitiesManager::saveXML()
{
	kdDebug() << k_funcinfo << "Saving global identities list to XML." << endl;

	TQString globalIdentitiesListFileName = locateLocal( "appdata", TQString::fromUtf8("global-identities.xml") );
	KSaveFile globalIdentitiesListFile(globalIdentitiesListFileName);
	if( globalIdentitiesListFile.status() == 0 )
	{
		TQTextStream *stream = globalIdentitiesListFile.textStream();
		stream->setEncoding( TQTextStream::UnicodeUTF8 );
		toXML().save( *stream, 4 );

		if ( globalIdentitiesListFile.close() )
		{
			return;
		}
		else
		{
			kdDebug(14000) << k_funcinfo << "Failed to write global identities list, error code is: " << globalIdentitiesListFile.status() << endl;
		}
	}
	else
	{
		kdWarning(14000) << k_funcinfo << "Couldn't open global identities list file " << globalIdentitiesListFileName
			<< ". Global Identities list not saved." << endl;
	}
}

const TQDomDocument GlobalIdentitiesManager::toXML()
{
	TQDomDocument doc;
	
	doc.appendChild(doc.createElement(TQString::fromUtf8("kopete-global-identities-list")));
	
	TQMapIterator<TQString, Kopete::MetaContact*> it;
	TQMapIterator<TQString, Kopete::MetaContact*> end = d->identitiesList.end();
	for(it = d->identitiesList.begin(); it != end; ++it)
	{
		kdDebug(14000) << k_funcinfo << "Saving " << it.key() << endl;
		TQDomElement identityMetaContactElement = it.data()->toXML(true); // Save minimal information.
		identityMetaContactElement.setTagName(TQString::fromUtf8("identity"));
		identityMetaContactElement.setAttribute(TQString::fromUtf8("name"), it.key());
		doc.documentElement().appendChild(doc.importNode(identityMetaContactElement, true));
	}

	return doc;
}

Kopete::MetaContact *GlobalIdentitiesManager::createNewMetaContact()
{
	Kopete::MetaContact *newMetaContact = new Kopete::MetaContact();
	TQPtrList<Kopete::Contact> contactList = Kopete::ContactList::self()->myself()->contacts();

	// Copy the contacts list to the new metacontact, so Kopete::Contact for SourceContact
	// will not be null.
	TQPtrListIterator<Kopete::Contact> it( contactList);
	for ( ; it.current(); ++it )
	{
		newMetaContact->addContact(it.current());
	}

	newMetaContact->setDisplayNameSource(Kopete::MetaContact::SourceCustom);
	newMetaContact->setPhotoSource(Kopete::MetaContact::SourceCustom);

	return newMetaContact;
}

Kopete::MetaContact *GlobalIdentitiesManager::createCopyMetaContact(Kopete::MetaContact *source)
{
	Kopete::MetaContact *copyMetaContactObject = createNewMetaContact();

	copyMetaContact(copyMetaContactObject, source);
	
	return copyMetaContactObject;
}

void GlobalIdentitiesManager::copyMetaContact(Kopete::MetaContact *destination, Kopete::MetaContact *source)
{
	destination->setDisplayName(source->customDisplayName());
	destination->setDisplayNameSource(source->displayNameSource());
	destination->setDisplayNameSourceContact(source->displayNameSourceContact());
	
	destination->setPhoto(source->customPhoto());
	destination->setPhotoSource(source->photoSource());
	destination->setPhotoSourceContact(source->photoSourceContact());
}

TQMap<TQString, Kopete::MetaContact*> GlobalIdentitiesManager::getGlobalIdentitiesList()
{
	return d->identitiesList;
}

#include "globalidentitiesmanager.moc"
