/* This file is part of the Keep project
   Copyright (C) 2005 Jean-Rémy Falleri <jr.falleri@laposte.net>

   Keep 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.

   Keep 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 Keep; if not, write to the
   Free Software Foundation, Inc.,
   51 Franklin Steet, Fifth Floor, Boston, MA 02110-1301, USA.           */

#include "keepkded.h"

#include <tqdir.h>
#include <tqfile.h>
#include <tqfileinfo.h>
#include <tqdatetime.h>
#include <kdebug.h>
#include <kprocess.h>
#include <krun.h>
#include <tdemessagebox.h>
#include <kstdguiitem.h>
#include <kstandarddirs.h>
#include <knotifyclient.h>
#include <tdelocale.h>
#include <keepsettings.h>

KeepKded::KeepKded(const TQCString &name): KDEDModule(name)
{
	m_logFilePath = locateLocal( "data", "keep/keep.log", true );

	m_manager = new RDBManager();
	connect( m_manager, TQ_SIGNAL(backupError(Backup,TQString)), this, TQ_SLOT(slotBackupError(Backup,TQString)) );
	connect( m_manager, TQ_SIGNAL(backupSuccess(Backup)), this, TQ_SLOT(slotBackupSuccess(Backup)) );

	slotCheckBackup();

	m_timer = new TQTimer(this);
	connect( m_timer, TQ_SIGNAL(timeout()), this, TQ_SLOT(slotCheckBackup()) );
	m_timer->start( 1000 * 60 * 60 );
}

KeepKded::~KeepKded()
{
	delete m_manager;
}

void KeepKded::slotBackupError(Backup backup,TQString errorMessage)
{
	if ( KeepSettings::notifyBackupError() )
	{
		KNotifyClient::userEvent(0,i18n("<p><b>An error occured making %1 backup:</b></p><p>%2</p>").arg(backup.source()).arg(errorMessage),16,4);
	}
	log("Backup Error",backup.source(),errorMessage);
}

void KeepKded::slotBackupSuccess(Backup backup)
{
	if ( KeepSettings::notifyBackupSuccess() )
	{
		KNotifyClient::userEvent(0,i18n("<p><b>Backup %1 successfully backuped to %2</b></p>").arg(backup.source()).arg(backup.dest()),16,1);
	}
	log("Backup Success",backup.source(),"Successfully backuped to: " + backup.dest() );
}

void KeepKded::log(TQString type,TQString backup,TQString message)
{
	TQString logMessage = TQDateTime::currentDateTime().toString(TQt::ISODate) + "\t" + type + "\t" + backup + "\t" + message;
	TQFile file( m_logFilePath );
	if ( file.open(IO_WriteOnly | IO_Append) )
	{
		TQTextStream stream( &file );
		stream << logMessage << "\n";
		file.close();
	}
}

void KeepKded::slotCheckBackup()
{
	kdDebug(7020) << "Launching previous backup analyse." << endl;	
	m_manager->slotCheckBackup();
}

extern "C"
{
	TDE_EXPORT KDEDModule *create_keep(const TQCString &name)
	{
		return new KeepKded(name);
	}
}


#include "keepkded.moc"
