/*
 *
 * Copyright (C) 2002 Stefan Hellwig <stefan@stefanhellwig.de>
 *
 *   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 <kapplication.h>
#include <kdebug.h>
#include <qdatastream.h>
#include <klocalizedstring.h>
#include <QtDBus/QDBusConnection>
#include <QtDBus/QDBusMessage>
#include <QtDBus/QDBusReply>

#include "savercontrol.h"

SaverControl::SaverControl()
{
    startup_saver_status = getScreenSaverStatus();
}


SaverControl::~SaverControl()
{
    // At the end: enable screensaver if it has been active on startup
    setScreenSaver(startup_saver_status);
}

void SaverControl::setScreenSaver(bool status)
{
    if (status) {
        enableScreenSaver();
    } else {
        disableScreenSaver();
    }
}

bool SaverControl::getScreenSaverStatus()
{
    QDBusMessage message = QDBusMessage::createMethodCall("org.freedesktop.ScreenSaver", "/ScreenSaver",
                                                          "org.freedesktop.ScreenSaver", "GetActive");

    QDBusReply<uint> reply = QDBusConnection::sessionBus().call( message );
    if (! reply.isValid()) {
        return static_cast<bool>(reply.value()) ;
    }
    return true;
}

bool SaverControl::disableScreenSaver()
{
    kDebug() << "Inhibit screensaver";

    QDBusMessage message = QDBusMessage::createMethodCall("org.freedesktop.ScreenSaver", "/ScreenSaver",
                                                          "org.freedesktop.ScreenSaver", "Inhibit");
    message << QString( "kdetv" );
    message << i18n( "We are watching TV" );

    QDBusReply<uint> reply = QDBusConnection::sessionBus().call( message );
    if (! reply.isValid()) {
        kWarning() << "Problem while trying to disable screensaver.";
        return false;
    }
    return true;
}

bool SaverControl::enableScreenSaver()
{
    kDebug() << "Un-inhibit screensaver";

    QDBusMessage message = QDBusMessage::createMethodCall("org.freedesktop.ScreenSaver", "/ScreenSaver",
                                                          "org.freedesktop.ScreenSaver", "Unhibit");

    QDBusReply<uint> reply = QDBusConnection::sessionBus().call( message );
    if (! reply.isValid()) {
        kWarning() << "Problem while trying to enable screensaver.";
        return false;
    }
    return true;
}
