// =============================================================================
// Zboard Config Utility
// Copyright (C) 2007  Matt Razza

// 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
// -------------------------------------------------------------------------------
// This file contains the main loop
// ===============================================================================

// Standard Includes
#include "zboard-inc.h"
#include "zboard-settings.h"
#include "zboard-info.h"
#include "zboard-xmodmap.h"

// Starts the zboard management system
void startSystem()
{
	// Create vars
	int iLoop;
	std::string sData = "", oldData = "", currentConfig = "", mapPath = "/usr/share/zboard-config/maps/";
	settingMan setting("/usr/share/zboard-config/zboard.conf");
	settingMan sysSetting("/usr/share/zboard-config/zboard-sys.conf");
	int iUseLoad = atoi(sysSetting.getSetting("SYS_USE_LOADKEYS").c_str());
	bool bUseLoad = false;

	if (iUseLoad == 1)
        bUseLoad = true;

    int iVerbose = atoi(sysSetting.getSetting("SYS_USE_LOADKEYS").c_str());
    bool bVerbose = false;

    if (iVerbose == 1)
        bVerbose = true;

	// Loop for ever
	while (true)
	{
		// Reset to defaults
		iLoop = 1;
		sData = "";
		currentConfig = "";

		sData = setting.getSettingNameByID(iLoop); //Start loop off

		// Loop until End of File
		while (sData != "ZINVALIDZ")
		{
			// Is the app running
			if (linuxProcInfo::isRunning(sData, bVerbose))
			{
				currentConfig = setting.getSetting(sData); //Get setting file
				break;
			}

			// Continue loop
			iLoop++;
			sData = setting.getSettingNameByID(iLoop);
		}

		// If no app found, set default config
		if (currentConfig == "")
			currentConfig = setting.getSetting("DEFAULT");

		// Update Needed?
		if (currentConfig != oldData)
		{
			mapInterface::bindNewFile(mapPath + currentConfig, bUseLoad);
			oldData = currentConfig;
		}

		sleep(5); // Wait 5 seconds before we scan again
	}
}
