/***************************************************************************
 *   Copyright (C) 2005 by Danny Kukawka                                   *
 *                         <dkukawka@suse.de>, <danny.kukawka@web.de>      *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of version 2 of the GNU General Public License     *
 *   as published by the Free Software Foundation.                         *
 *                                                                         *
 *   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.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.          *
 ***************************************************************************/

/*!
 * \file 	settings.cpp
 * \brief 	In this file can be found the settings ( read ) related code.
 * \author 	Danny Kukawka, <dkukawka@suse.de>, <danny.kukawka@web.de>
 * \date    	2005
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

// KDE Header
#include <tdelocale.h>

// TQt Header

// own headers
#include "settings.h"

/*! This is the default constructor of the class Settings. */
Settings::Settings()
{
	tdeconfig = new TDEConfig("tdepowersaverc", true );
	kde = new KDE_Settings();
	load_kde();
	load_general_settings();
}

/*! This is the default destructor of the class Settings. */
Settings::~Settings()
{
	delete tdeconfig;
	delete kde;
}


/*!
 * Loads the scheme settings from tdepowersaverc and fills the related variables.
 * \param schemeName TQString with the name (realname not i18n() version) of the
 *		     scheme which setting should be load. If the scheme could not
 *		     be loaded, this function try to load "default-scheme"
 * \return the result of the load
 * \retval true  if the settings could be loaded
 * \retval false if there was no group named like schemeName or named "default-scheme"
 */
bool Settings::load_scheme_settings(TQString schemeName){

	tdeconfig->reparseConfiguration();

	if( schemeName == "Performance" || schemeName == i18n("Performance"))
		 schemeName = "Performance";
	else if( schemeName == "Powersave" || schemeName == i18n("Powersave"))
		 schemeName = "Powersave";
	else if( schemeName == "Presentation" || schemeName == i18n("Presentation"))
		 schemeName = "Presentation";
	else if( schemeName == "Acoustic" || schemeName == i18n("Acoustic"))
		 schemeName = "Acoustic";

	if(tdeconfig->hasGroup(schemeName) || tdeconfig->hasGroup("default-scheme") ){
		if(tdeconfig->hasGroup(schemeName)) tdeconfig->setGroup(schemeName);
		else {
			// fallback to 'default-scheme'
			tdeconfig->setGroup("default-scheme");
			schemeName = "default-scheme";
		}
		currentScheme = schemeName;

		specSsSettings = tdeconfig->readBoolEntry("specSsSettings",false);
		disableSs = tdeconfig->readBoolEntry("disableSs",false);
		blankSs = tdeconfig->readBoolEntry("blankSs",false);
		specPMSettings = tdeconfig->readBoolEntry("specPMSettings",false);
		disableDPMS = tdeconfig->readBoolEntry("disableDPMS",false);

		int i_standby = tdeconfig->readNumEntry("standbyAfter", -1);
		if (i_standby >= 0) standbyAfter = i_standby;
		else {
			tdeconfig->setGroup("default-scheme");
			i_standby = tdeconfig->readNumEntry("standbyAfter", -1);
			if(i_standby >= 0) {
				standbyAfter = i_standby;
			}
			else standbyAfter = 0;
			// reset the group
			tdeconfig->setGroup(schemeName);
		}

		int i_suspend = tdeconfig->readNumEntry("suspendAfter", -1);
		if (i_suspend >= 0) suspendAfter = i_suspend;
		else {
			tdeconfig->setGroup("default-scheme");
			i_suspend = tdeconfig->readNumEntry("suspendAfter", -1);
			if(i_suspend >= 0) {
				suspendAfter = i_suspend;
			}
			else suspendAfter = 0;
			// reset the group
			tdeconfig->setGroup(schemeName);
		}

		int i_poweroff = tdeconfig->readNumEntry("powerOffAfter", -1);
		if (i_poweroff >= 0) powerOffAfter = i_poweroff;
		else {
			tdeconfig->setGroup("default-scheme");
			i_poweroff = tdeconfig->readNumEntry("powerOffAfter", -1);
			if(i_poweroff >= 0) {
				powerOffAfter = i_poweroff;
			}
			else powerOffAfter = 0;
			// reset the group
			tdeconfig->setGroup(schemeName);
		}

		brightness = tdeconfig->readBoolEntry("enableBrightness",false);
		brightnessValue = tdeconfig->readNumEntry("brightnessPercent", -1);
		if (brightnessValue == -1) {
			tdeconfig->setGroup("default-scheme");
			brightnessValue = tdeconfig->readNumEntry("brightnessPercent", 100);
			// reset the group
			tdeconfig->setGroup(schemeName);
		}

		int i_autoInactiveActionAfter = tdeconfig->readNumEntry("autoInactiveActionAfter", -1);
		if (i_autoInactiveActionAfter >= 0) autoInactiveActionAfter = i_autoInactiveActionAfter;
		else {
			tdeconfig->setGroup("default-scheme");
			i_autoInactiveActionAfter = tdeconfig->readNumEntry("autoInactiveActionAfter", -1);
			if(i_autoInactiveActionAfter >= 0) {
				autoInactiveActionAfter = i_autoInactiveActionAfter;
			}
			else autoInactiveActionAfter = 0;
			// reset the group
			tdeconfig->setGroup(schemeName);
		}

		TQString _autoInactiveAction = tdeconfig->readEntry("autoInactiveAction", "NULL");
		if( _autoInactiveAction != "NULL") {
			autoInactiveAction = _autoInactiveAction;
		}
		else {
			tdeconfig->setGroup("default-scheme");
			_autoInactiveAction = tdeconfig->readEntry("autoInactiveAction", "NULL");
			if(_autoInactiveAction != "NULL") autoInactiveAction = _autoInactiveAction;
			else autoInactiveAction = "_NONE_";
			// reset the group
			tdeconfig->setGroup(schemeName);
		}

		autoSuspend = tdeconfig->readBoolEntry("autoSuspend",false);
		autoInactiveSBlistEnabled = tdeconfig->readBoolEntry("autoInactiveSchemeBlacklistEnabled",false);
		autoInactiveSBlist = tdeconfig->readListEntry("autoInactiveSchemeBlacklist", ',');

		int i_autoDimmAfter = tdeconfig->readNumEntry("autoDimmAfter", -1);
		if (i_autoDimmAfter >= 0) autoDimmAfter = i_autoDimmAfter;
		else {
			tdeconfig->setGroup("default-scheme");
			i_autoDimmAfter = tdeconfig->readNumEntry("autoDimmAfter", -1);
			if(i_autoDimmAfter >= 0) {
				autoDimmAfter = i_autoDimmAfter;
			}
			else autoDimmAfter = 0;
			// reset the group
			tdeconfig->setGroup(schemeName);
		}

		int i_autoDimmTo = tdeconfig->readNumEntry("autoDimmTo", -1);
		if (i_autoDimmTo >= 0) autoDimmTo = i_autoDimmTo;
		else {
			tdeconfig->setGroup("default-scheme");
			i_autoDimmTo = tdeconfig->readNumEntry("autoDimmAfter", -1);
			if(i_autoDimmTo >= 0) {
				autoDimmTo = i_autoDimmTo;
			}
			else autoDimmTo = 0;
			// reset the group
			tdeconfig->setGroup(schemeName);
		}

		autoDimm = tdeconfig->readBoolEntry("autoDimm",false);
		autoDimmSBlistEnabled = tdeconfig->readBoolEntry("autoDimmSchemeBlacklistEnabled",false);
		autoDimmSBlist = tdeconfig->readListEntry("autoDimmSchemeBlacklist", ',');

		disableNotifications = tdeconfig->readBoolEntry("disableNotifications",false);

		TQString _cpufreqpolicy =  tdeconfig->readEntry("cpuFreqPolicy", "NULL");
		if( _cpufreqpolicy == "NULL") {
			tdeconfig->setGroup("default-scheme");
			_cpufreqpolicy = tdeconfig->readEntry("cpuFreqPolicy", "NULL");
			// reset the group
			tdeconfig->setGroup(schemeName);
		}
		if (_cpufreqpolicy.startsWith("DYNAMIC")) {
			cpuFreqPolicy = DYNAMIC;
		} else if (_cpufreqpolicy.startsWith("PERFORMANCE")) {
			cpuFreqPolicy = PERFORMANCE;
		} else if (_cpufreqpolicy.startsWith("POWERSAVE")) {
			cpuFreqPolicy = POWERSAVE;
		} else {
			// set as default
			cpuFreqPolicy = DYNAMIC;
		}

		cpuFreqDynamicPerformance = tdeconfig->readNumEntry("cpuFreqDynamicPerformance", -1);
		if( cpuFreqDynamicPerformance == -1) {
			tdeconfig->setGroup("default-scheme");
			cpuFreqDynamicPerformance = tdeconfig->readNumEntry("cpuFreqDynamicPerformance", 51);
			// reset the group
			tdeconfig->setGroup(schemeName);
		}

		return true;
	}
	else return false;
}


/*!
 * Loads the general settings from tdepowersaverc and fills the related variables.
 * \return the result of the load
 * \retval true  if the settings could be loaded
 * \retval false if there was no group named 'General'
 */
bool Settings::load_general_settings(){

	tdeconfig->reparseConfiguration();

	if(tdeconfig->hasGroup("General")) {
		tdeconfig->setGroup("General");

		lockOnSuspend = tdeconfig->readBoolEntry("lockOnSuspend",true);
		lockOnLidClose = tdeconfig->readBoolEntry("lockOnLidClose",true);
		autostart = tdeconfig->readBoolEntry("Autostart",false);
		autostartNeverAsk = tdeconfig->readBoolEntry("AutostartNeverAsk",false);
		psMsgAsPassivePopup = tdeconfig->readBoolEntry("psMsgAsPassivePopup",false);
		forceDpmsOffOnLidClose = tdeconfig->readBoolEntry("forceDpmsOffOnLidClose",false);
		unmountExternalOnSuspend = tdeconfig->readBoolEntry("unmountExternalOnSuspend",true);

		lockmethod = tdeconfig->readEntry("lockMethod", "NULL");
		if(lockmethod == "NULL") lockmethod = "automatic";

		autoInactiveGBlist = tdeconfig->readListEntry("autoInactiveBlacklist", ',');
		autoDimmGBlist = tdeconfig->readListEntry("autoDimmBlacklist", ',');

		autoSuspendCountdown = tdeconfig->readBoolEntry("AutoSuspendCountdown", false);
		autoSuspendCountdownTimeout = tdeconfig->readNumEntry("AutoSuspendCountdownTimeOut", 30);

		timeToFakeKeyAfterLock = tdeconfig->readNumEntry("timeToFakeKeyAfterLock", 5000);

		schemes = tdeconfig->readListEntry("schemes", ',');
		ac_scheme = tdeconfig->readEntry("ac_scheme", "Performance");
		battery_scheme = tdeconfig->readEntry("battery_scheme", "Powersave");

		// Read battery levels and related actions
		batteryWarningLevel = tdeconfig->readNumEntry("batteryWarning", 12);
		batteryLowLevel = tdeconfig->readNumEntry("batteryLow", 7);
		batteryCriticalLevel = tdeconfig->readNumEntry("batteryCritical", 2);

		batteryWarningLevelAction = mapActionToType(tdeconfig->readEntry("batteryWarningAction",""));
		if (batteryWarningLevelAction == BRIGHTNESS) {
			batteryWarningLevelActionValue = tdeconfig->readNumEntry("batteryWarningActionValue", -1);
		}
		batteryLowLevelAction = mapActionToType(tdeconfig->readEntry("batteryLowAction",""));
		if (batteryLowLevelAction == BRIGHTNESS) {
			batteryLowLevelActionValue = tdeconfig->readNumEntry("batteryLowActionValue", -1);
		}
		batteryCriticalLevelAction = mapActionToType(tdeconfig->readEntry("batteryCriticalAction",""));
		if (batteryCriticalLevelAction == BRIGHTNESS) {
			batteryCriticalLevelActionValue = tdeconfig->readNumEntry("batteryCriticalActionValue", -1);
		}

		lidcloseAction = mapActionToType(tdeconfig->readEntry("ActionOnLidClose",""));
		if (lidcloseAction == BRIGHTNESS) {
			lidcloseActionValue =  tdeconfig->readNumEntry("ActionOnLidCloseValue", -1);
		}
		// avoid logout dialog since this make no sence with lidclose
		if (lidcloseAction == LOGOUT_DIALOG) {
			lidcloseAction = NONE;
		}

		powerButtonAction = mapActionToType(tdeconfig->readEntry("ActionOnPowerButton",""));
		if (powerButtonAction == BRIGHTNESS) {
			powerButtonActionValue =  tdeconfig->readNumEntry("ActionOnPowerButtonValue", -1);
		}

		sleepButtonAction = mapActionToType(tdeconfig->readEntry("ActionOnSuspendButton",""));
		if ((sleepButtonAction != GO_SUSPEND2RAM) && (sleepButtonAction != GO_SUSPEND2DISK) && 
		    (sleepButtonAction != GO_FREEZE) && (sleepButtonAction != GO_SUSPEND_HYBRID)) {
			sleepButtonAction = NONE;
		}

		s2diskButtonAction = mapActionToType(tdeconfig->readEntry("ActionOnS2DiskButton",""));
		if ((s2diskButtonAction != GO_SUSPEND2RAM) && (s2diskButtonAction != GO_SUSPEND2DISK) &&
		    (s2diskButtonAction != GO_FREEZE) && (s2diskButtonAction != GO_SUSPEND_HYBRID)) {
			s2diskButtonAction = NONE;
		}

		return true;
	}
	else return false;
}


/*!
 * Map the string value from the config file to the type from \ref action
 * \param _action	a TQString to map
 * \return a integer value with the result of the mapping as \ref action
 */
action Settings::mapActionToType (TQString _action) {

	if (_action.isEmpty()) {
		return NONE;
	} else if (_action.startsWith("SHUTDOWN")) {
		return GO_SHUTDOWN;
	} else if (_action.startsWith("LOGOUT_DIALOG")) {
		return LOGOUT_DIALOG;
	} else if (_action.startsWith("SUSPEND2DISK")) {
		return GO_SUSPEND2DISK;
	} else if (_action.startsWith("SUSPEND_HYBRID")) {
		return GO_SUSPEND_HYBRID;
	} else if (_action.startsWith("SUSPEND2RAM")) {
		return GO_SUSPEND2RAM;
	} else if (_action.startsWith("FREEZE")) {
		return GO_FREEZE;
	} else if (_action.startsWith("CPUFREQ_POWERSAVE")) {
		return CPUFREQ_POWERSAVE;
	} else if (_action.startsWith("CPUFREQ_DYNAMIC")) {
		return CPUFREQ_DYNAMIC;
	} else if (_action.startsWith("CPUFREQ_PERFORMANCE")) {
		return CPUFREQ_PERFORMANCE;
	} else if (_action.startsWith("BRIGHTNESS")) {
		return BRIGHTNESS;
	} else {
		return UNKNOWN_ACTION;
	}
}

/*!
 * Loads the default KDE Settings from the different configfiles and store
 * them to a \ref KDE_Settings 'object'.
 * \retval true  if the settings could be loaded
 * \retval false if there was a error/problem
 */
void Settings::load_kde(){
	TDEConfig *_tdeconfig = new TDEConfig("kcmdisplayrc", true );

	/* KDE settings [DisplayEnergy] from kcmdisplayrc */
	if(_tdeconfig->hasGroup("DisplayEnergy")) {
		_tdeconfig->setGroup("DisplayEnergy");
		kde->displayEnergySaving = _tdeconfig->readBoolEntry("displayEnergySaving", true);
		kde->displayStandby = _tdeconfig->readNumEntry("displayStandby", 7);
		kde->displaySuspend = _tdeconfig->readNumEntry("displaySuspend", 13);
		kde->displayPowerOff = _tdeconfig->readNumEntry("displayPowerOff", 19);
	}
        delete _tdeconfig;
	_tdeconfig = new TDEConfig("kdesktoprc", true );
	/* KDE settings [ScreenSaver] from kdesktoprc */
	if(_tdeconfig->hasGroup("ScreenSaver")) {
		_tdeconfig->setGroup("ScreenSaver");
		kde->enabled = _tdeconfig->readBoolEntry("Enabled", true);
		kde->lock = _tdeconfig->readBoolEntry("Lock", true);

		TQString _savername = _tdeconfig->readEntry("Saver", "KBlankscreen.desktop");
		if (_savername.startsWith("KBlankscreen.desktop"))
			kde->blanked = true;
		else
			kde->blanked = false;
	}
	delete _tdeconfig;
}

