/***************************************************************************
 *                                                                         *
 *   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.                                   *
 *                                                                         *
 ***************************************************************************/
/*
Author: Christian Hubinger <chubinger@irrsinnig.org>, (C) 2001-2008
*/
#include "kmftransaction.h"

// KDE includes
#include <kdebug.h>
#include <tdelocale.h>

// Project includes
#include "netfilterobject.h"
#include "kmfundoengine.h"

namespace KMF {

KMFTransaction::KMFTransaction( const TQString& transactionName, NetfilterObject* highestAffectedObject ) {
	m_transactionName = transactionName;
	m_uuID = TQUuid::createUuid();
	m_objectUuid = highestAffectedObject->uuid();
	m_undoXML = highestAffectedObject->getXMLSniplet();
	kdDebug() << "Created " << toString() <<  endl;
}

KMFTransaction::~KMFTransaction() {}

void KMFTransaction::commit() {
	NetfilterObject* obj = NetfilterObject::findObject( m_objectUuid );
	if ( ! obj )  {
		return;
	}
	m_redoXML = obj->getXMLSniplet();
}

NetfilterObject* KMFTransaction::undo() {
	NetfilterObject* obj = NetfilterObject::findObject( m_objectUuid );
	if ( ! obj ) {
		KMFUndoEngine::instance()->log( i18n("KMFTransaction::undo() No object found with uuid: %1").arg( m_objectUuid ), KMFError::WARNING, 0 );
		return 0;
	}
	if( m_undoXML.isNull() ) {
		return 0;
	}
	TQDomDocument doc;
	doc.setContent( m_undoXML );
	TQStringList * errors = new TQStringList();
	obj->loadXML( doc, *errors );
	return obj;
}

NetfilterObject* KMFTransaction::redo() {
	NetfilterObject* obj = NetfilterObject::findObject( m_objectUuid );
	if ( ! obj ) {
		KMFUndoEngine::instance()->log( i18n("KMFTransaction::redo() No object found with uuid: %1").arg( m_objectUuid ), KMFError::WARNING, 0 );
		return 0;
	}
	if ( m_redoXML.isNull() ) {
		return 0;
	}
	TQDomDocument doc;
	doc.setContent( m_redoXML );
	TQStringList * errors = new TQStringList();
	obj->loadXML( doc, *errors );
	return obj;
}

const TQString& KMFTransaction::toString() {
	TQString s = "";
	s.append( i18n("Transaction: %1 uuid: %2\n" ).arg( name() ).arg( uuid().toString() ) );
	s.append( i18n("-- Changed ObjectUuid: %1").arg( m_objectUuid.toString() ) );
	return *( new TQString( s ) );
}

}
