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

#include <tqcolor.h>
#include <tqlayout.h>
#include <tqvariant.h>
#include <dcopclient.h>
#include <tdeactioncollection.h>
#include <kstdaction.h>
#include <kdebug.h>
#include <tdelocale.h>
#include <kactivelabel.h>
#include <tdeapplication.h>
#include <kled.h>
#include <kpushbutton.h>
#include <tdemessagebox.h>
#include <kiconloader.h>
#include <tdeconfigdialog.h>

#include "backupconfig.h"
#include "addbackupwizard.h"
#include "restorebackupwizard.h"
#include "forcebackupdialog.h"
#include "backupconfigdialog.h"
#include "generalconfigview.h"
#include "rdbmanager.h"
#include "keepsettings.h"
#include "logdialog.h"

KeepMainWindow::KeepMainWindow(TQWidget *parent, const char *name): TDEMainWindow(parent,name)
{
	setCaption(i18n("Backup System"));

	m_actionView = new ActionView(this);
	TDEIconLoader *icons = TDEGlobal::iconLoader();
	m_actionView->m_btnAddWizard->setPixmap(icons->loadIcon("add_backup",TDEIcon::Toolbar,32));
	m_actionView->m_btnRestoreWizard->setPixmap(icons->loadIcon("restore_dir",TDEIcon::Toolbar,32));
	m_actionView->m_btnForce->setPixmap(icons->loadIcon("force_backup",TDEIcon::Toolbar,32));
	m_actionView->m_btnBackupConfig->setPixmap(icons->loadIcon("configure",TDEIcon::Toolbar,32));
	m_actionView->m_btnLog->setPixmap(icons->loadIcon("text-x-log",TDEIcon::Toolbar,32));
	
	slotRefreshGUI();

	setCentralWidget(m_actionView);

	initActions();
	initConnections();

	resize( minimumSizeHint() );

	createGUI(0L);

	RDBManager manager;
	if ( !manager.isRDB() )
		slotCheckRDB();
}

KeepMainWindow::~KeepMainWindow()
{
}

void KeepMainWindow::initActions()
{
	KStdAction::quit(this, TQ_SLOT(close()), actionCollection());
	new TDEAction( i18n("Check rdiff-backup"), "application-vnd.tde.info", "", this, TQ_SLOT(slotCheckRDB()), actionCollection(), "check_rdiff-backup" );
	new TDEAction( i18n("Configure backups"), "configure", "", this, TQ_SLOT(slotConfigureBackup()), actionCollection(), "configure_backups" );
	new TDEAction( i18n("Configure"), "configure", "", this, TQ_SLOT(slotConfigure()), actionCollection(), "configure_keep" );
	new TDEAction( i18n("Add Backup"), "add_backup", "", this, TQ_SLOT(slotAddBackupWizard()), actionCollection(), "add_backup" );
	new TDEAction( i18n("Restore Backup"), "restore_dir", "", this, TQ_SLOT(slotRestoreBackupWizard()), actionCollection(), "restore_backup" );
	new TDEAction( i18n("Backup Now"), "force_backup", "", this, TQ_SLOT(slotForceBackup()), actionCollection(), "force_backup" );
	new TDEAction( i18n("View log"), "text-x-log", "", this, TQ_SLOT(slotViewLog()), actionCollection(), "view_log");
}

void KeepMainWindow::initConnections()
{
	connect( m_actionView->m_btnAddWizard, TQ_SIGNAL( clicked()), this, TQ_SLOT( slotAddBackupWizard() ) );
	connect( m_actionView->m_btnRestoreWizard, TQ_SIGNAL( clicked()), this, TQ_SLOT( slotRestoreBackupWizard() ) );
	connect( m_actionView->m_btnForce, TQ_SIGNAL( clicked()), this, TQ_SLOT( slotForceBackup() ) );
	connect( m_actionView->m_btnBackupConfig, TQ_SIGNAL( clicked()), this, TQ_SLOT( slotConfigureBackup() ) );
	connect( m_actionView->m_btnLog, TQ_SIGNAL( clicked()), this, TQ_SLOT( slotViewLog() ) );
	connect( m_actionView->m_btnLoadDaemon, TQ_SIGNAL( clicked()), this, TQ_SLOT( slotLoadDaemon() ) );
	connect( m_actionView->m_btnUnloadDaemon, TQ_SIGNAL( clicked()), this, TQ_SLOT( slotUnloadDaemon() ) );
	connect( m_actionView->m_btnReloadDaemon, TQ_SIGNAL( clicked()), this, TQ_SLOT( slotReloadDaemon() ) );
}

void KeepMainWindow::slotRefreshGUI()
{
	// Sets the Keep Daemon (KDED) State
	if ( backupSystemRunning() )
	{
		m_actionView->m_lblDaemonState->setText(i18n("<p align=\"right\"><b>Ok</b></p>"));
		m_actionView->m_btnLoadDaemon->setEnabled(false);
		m_actionView->m_btnUnloadDaemon->setEnabled(true);
		m_actionView->m_btnReloadDaemon->setEnabled(true);
		slotDaemonAlertState(false);
	}
	else
	{
		m_actionView->m_lblDaemonState->setText(i18n("<p align=\"right\"><b>Not Running</b></p>"));
		m_actionView->m_btnLoadDaemon->setEnabled(true);
		m_actionView->m_btnUnloadDaemon->setEnabled(false);
		m_actionView->m_btnReloadDaemon->setEnabled(false);
		slotDaemonAlertState(true);
	}
}

void KeepMainWindow::slotCheckRDB()
{
	RDBManager manager;
	if ( manager.isRDB() )
		KMessageBox::information(this, i18n("<b>The application rdiff-backup has been detected on your system.</b><br><br> You're running version %1 of rdiff-backup.").arg(manager.RDBVersion()));
	else
		KMessageBox::error(this,i18n("<b>The application rdiff-backup has not been detected on your system.</b><br><br>If rdiff-backup is not installed, Keep will not be able to make backups. To fix this problem, install rdiff-backup on your system."));
	
}

void KeepMainWindow::slotForceBackup()
{
	ForceBackupDialog *force = new ForceBackupDialog(this);
	force->show();
}

void KeepMainWindow::slotViewLog()
{
	LogDialog *logDialog = new LogDialog(this);
	logDialog->show();
}

void KeepMainWindow::slotConfigureBackup()
{
	BackupConfigDialog *backupConfig = new BackupConfigDialog(this);
	backupConfig->show();
}

void KeepMainWindow::slotConfigure()
{
	//An instance of your dialog could be already created and could be cached, 
	//in which case you want to display the cached dialog instead of creating 
	//another one 
	if ( TDEConfigDialog::showDialog( "settings" ) ) 
        	return; 
 
	//TDEConfigDialog didn't find an instance of this dialog, so lets create it : 
	TDEConfigDialog* dialog = new TDEConfigDialog( this, "settings", KeepSettings::self() ); 
	GeneralConfigView* generalConfigView =  new GeneralConfigView( 0, "generalConfigView" ); 
 
	dialog->addPage( generalConfigView, i18n("General"), "general" ); 
 
	dialog->show();
}

void KeepMainWindow::slotAddBackupWizard()
{
	AddBackupWizard *addBackupWizard = new AddBackupWizard(this, "addBackupWizard");
	connect( addBackupWizard, TQ_SIGNAL( backupSetted(Backup)), this, TQ_SLOT( slotAddBackup(Backup) ) );
	addBackupWizard->show();
}

void KeepMainWindow::slotAddBackup(Backup backup)
{
	BackupConfig *backupConfig = new BackupConfig();
	backupConfig->addBackup(backup);
	delete backupConfig;
}

void KeepMainWindow::slotRestoreBackupWizard()
{
	RestoreBackupWizard *restoreBackupWizard = new RestoreBackupWizard(this, "restoreBackupWizard");
	restoreBackupWizard->show();
}

void KeepMainWindow::slotDaemonAlertState(bool state)
{
	if ( !state )
	{
		m_actionView->m_ledDaemonState->setColor(TQt::green);
	}
	else
	{
		m_actionView->m_ledDaemonState->setColor(TQt::red);
	}
}

bool KeepMainWindow::backupSystemRunning()
{
	QCStringList modules;
	TQCString replyType;
	TQByteArray replyData;

	if ( !kapp->dcopClient()->call( "kded", "kded", "loadedModules()", TQByteArray(), replyType, replyData ) )
		return false;
	else
	{
		if ( replyType == "QCStringList" ) 
		{
			TQDataStream reply( replyData, IO_ReadOnly );
			reply >> modules;
		}
	}
	QCStringList::ConstIterator end( modules.end() );
	for ( QCStringList::ConstIterator it = modules.begin(); it != end; ++it )
	{
		if ( *it == "keep" )
		return true;
	}
	return false;
}

void KeepMainWindow::slotLoadDaemon()
{
	TQCString service = "keep";

	TQByteArray data, replyData;
	TQCString replyType;
	TQDataStream arg( data, IO_WriteOnly );
	arg << service;
	if ( kapp->dcopClient()->call( "kded", "kded", "loadModule(TQCString)", data, replyType, replyData ) )
	{
		TQDataStream reply( replyData, IO_ReadOnly );
		if ( replyType == "bool" )
		{
			bool result;
			reply >> result;
			if ( !result )
			{
				
				return;
			}
		}
		else
		{
			KMessageBox::error( this, i18n( "Incorrect reply from KDED." ) );
			return;
		}
	}
	else
	{
		KMessageBox::error( this, i18n( "Unable to contact KDED." ) );
		return;
	}
	slotRefreshGUI();
}

void KeepMainWindow::slotUnloadDaemon()
{
	TQCString service = "keep";

	TQByteArray data;
	TQDataStream arg( data, IO_WriteOnly );

	arg << service;
	if ( !kapp->dcopClient()->send( "kded", "kded", "unloadModule(TQCString)", data ) )
	{
		KMessageBox::error( this, i18n( "Unable to stop service." ) );
		return;
	}
	slotRefreshGUI();
}

void KeepMainWindow::slotReloadDaemon()
{
	slotUnloadDaemon();
	slotLoadDaemon();
}

#include "keepmainwindow.moc"
