/***************************************************************************
 *   Copyright (C) 2008 by Andreas Silberstorff   *
 *   taki@Rivendell   *
 *                                                                         *
 *   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.                                   *
 *                                                                         *
 *   This program 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 this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/


#include "kalva2.h"
#include "kalvaview.h"
#include "settings.h"
#include "lib/pluginsystem/pluginsettingspage.h"
#include "lib/prefs/generalsettingspage.h"

#include <QtGui/QDropEvent>
#include <QtGui/QPainter>

#include <KApplication>
#include <KConfigDialog>
#include <KStatusBar>
#include <KAction>
#include <KActionCollection>
#include <KStandardAction>
#include <KToggleAction>
#include <KSystemTrayIcon>
#include <KIcon>
#include <KMessageBox>
#include <KDebug>
#include <KDE/KLocale>

kalva2::kalva2()
    : KXmlGuiWindow(),
      m_view(new kalvaview(this))
{
	// accept dnd
	setAcceptDrops(true);

	// tell the KXmlGuiWindow that this is indeed the main widget
	setCentralWidget(m_view);
	setMaximumSize(m_view->size());

	// then, setup our actions
	setupActions();

	// add a status bar
	statusBar()->show();

	readConfig();
	setupSystemTray();

	// a call to KXmlGuiWindow::setupGUI() populates the GUI
	// with actions, using KXMLGUI.
	// It also applies the saved mainwindow settings, if any, and ask the
	// mainwindow to automatically save settings if changed: window size,
	// toolbar position, icon size, etc.
	setupGUI();


	if (m_startDocked) {
		hide();
//	}  else {
//		ipOfTheDay();
	}
	m_shuttingDown  = false;
}

kalva2::~kalva2()
{
}

void kalva2::setupActions()
{
	KStandardAction::quit(qApp, SLOT(quit()), actionCollection());
	KStandardAction::close(this, SLOT(slotQuit()), actionCollection());

	KStandardAction::preferences(this, SLOT(optionsPreferences()), actionCollection() );

	m_toggleDockOnCloseAction = new KToggleAction(
		i18n( "&Stay in System Tray on Close" ),
		actionCollection() );
	m_toggleSystemTrayAction = new KToggleAction(
		i18n( "&Dock in System Tray" ),
		actionCollection() );
//     KStdAction::tipOfDay(
//            this,                     SLOT( slotTipOfTheDay() ),
//            actionCollection()
//            )->setWhatsThis(
//               i18n("This shows useful tips on the use of this application.")
//            );

	connect( m_toggleSystemTrayAction, SIGNAL( toggled( bool ) ),
		this, SLOT( slotToggleSystemTray( bool ) ) );
}

void kalva2::readConfig()
{
	m_startDocked = Settings::self()->start_docked();
	m_toggleSystemTrayAction->setChecked( Settings::self()->dock_in_systemtray() );
	m_toggleDockOnCloseAction->setChecked( Settings::self()->dock_on_close() );
//     KConfigGroup kalvaConfig(KGlobal::config(), "Kalva2");
//    restoreWindowSize(KGlobal::config());
}

void kalva2::saveConfig()
{
    Settings::self()->setStart_docked( m_startDocked );
    Settings::self()->setDock_in_systemtray( m_toggleSystemTrayAction->isChecked() );
    Settings::self()->setDock_on_close( m_toggleDockOnCloseAction->isChecked() );
//     KConfigGroup kalvaConfig(KGlobal::config(), "Kalva2");
//     saveWindowSize(KGlobal::config());
//     KGlobal::config()->sync();
}

bool kalva2::queryExit()
{
    m_startDocked = !isVisible();
    hide();

    delete m_systemTray;
    m_systemTray = 0;

    saveConfig();
    return true;
}

bool kalva2::queryClose()
{
	if( !m_shuttingDown &&
	    !( kapp->sessionSaving() ) &&
	    m_systemTray &&
	    m_toggleDockOnCloseAction->isChecked() ) {
		KMessageBox::information(this,
			i18n( "<qt>Closing the main window will keep Kalva running in the system tray. "
			      "Use Quit from the File menu to quit the application.</qt>" ),
			i18n( "Docking in System Tray" ),
			"hideOnCloseInfo" );
		hide();
		return false;
	} else {
		return true;
	}
}

void kalva2::setupSystemTray()
{
	if( m_toggleSystemTrayAction && m_toggleSystemTrayAction->isChecked() ) {
		m_systemTray = new KSystemTrayIcon( KIcon( "kalva2" ), this );
		m_systemTray->show();
		m_toggleDockOnCloseAction->setEnabled( true );
		connect(m_systemTray, SIGNAL( quitSelected()), this, SLOT( slotAboutToQuit() ) );
	} else {
		m_systemTray = 0;
		m_toggleDockOnCloseAction->setEnabled( false );
	}
}

void kalva2::slotToggleSystemTray(bool enabled)
{
	if(enabled && !m_systemTray) {
		setupSystemTray();
	} else if(!enabled && m_systemTray) {
		delete m_systemTray;
		m_systemTray = 0;
		m_toggleDockOnCloseAction->setEnabled( false );
	}
}

void kalva2::slotAboutToQuit()
{
    m_shuttingDown = true;
}

void kalva2::slotQuit()
{
	if (queryClose()) {
		m_shuttingDown = true;
		kapp->quit();
	}
}

void kalva2::optionsPreferences()
{
	kDebug() << "optionsPreferences()";
	if ( KConfigDialog::showDialog( "settings" ) )  {
		return;
	}
	KConfigDialog *dialog = new KConfigDialog(this, "settings", Settings::self());
	dialog->setMinimumSize( minimumSizeHint() );
	dialog->setMaximumSize( maximumSizeHint() );

	Kalva::GeneralSettingsPage* generalSettings = new Kalva::GeneralSettingsPage();
	kDebug() << "generalSettings created";
	dialog->addPage(generalSettings,
		Settings::self(),
		i18n("General settings"),
		"kalva2_generalsetting");
	kDebug() << "generalSettings added";
	connect(dialog, SIGNAL(settingsChanged(const QString&)), generalSettings, SLOT(loadSettings()));

	// add plugin settings page to the config dialog
	dialog->addPage( new KalvaPluginSystem::PluginSettingsPage( dialog ), i18n("Plugins"), "plugin_setting" );

	// add config pages provided by the perspectives to the config dialog
	m_view->addToConfigDialog( dialog );

	connect(dialog, SIGNAL(settingsChanged(QString)), m_view, SLOT(settingsChanged()));
	dialog->setAttribute( Qt::WA_DeleteOnClose );
	dialog->show();
}

QSize kalva2::minimumSizeHint() const
{
	int x = Settings::max_size_width();
	int y = Settings::max_size_height();
	return QSize(x, y);
}

QSize kalva2::maximumSizeHint() const
{
	int x = Settings::max_size_width();
	int y = Settings::max_size_height();
	return QSize(x, y);
}

#include "kalva2.moc"
