/*
  Copyright (C) 2004 Kimmo Pekkola

  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.
*/

#pragma warning(disable: 4996)

#include <windows.h>
#include "AdvancedCPU.h"
#include <string>
#include <vector>
#include <map>
#include "..\..\Library\Export.h"	// Rainmeter's exported functions

ULONGLONG GetPerfData(PCTSTR ObjectName, PCTSTR InstanceName, PCTSTR CounterName);

struct CPUMeasure
{
	std::vector< std::wstring > includes;
	std::vector< std::wstring > excludes;
	ULONGLONG oldValue;
};

static CPerfTitleDatabase g_CounterTitles( PERF_TITLE_COUNTER );
static std::map<UINT, CPUMeasure*> g_CPUMeasures;

void SplitName(WCHAR* names, std::vector< std::wstring >& splittedNames)
{
	WCHAR* token;
	
	token = wcstok(names, L";");
	while(token != NULL)
	{
		splittedNames.push_back(token);
		token = wcstok(NULL, L";");
	}
}

/*
  This function is called when the measure is initialized.
  The function must return the maximum value that can be measured. 
  The return value can also be 0, which means that Rainmeter will
  track the maximum value automatically. The parameters for this
  function are:

  instance  The instance of this DLL
  iniFile   The name of the ini-file (usually Rainmeter.ini)
  section   The name of the section in the ini-file for this measure
  id        The identifier for the measure. This is used to identify the measures that use the same plugin.
*/
UINT Initialize(HMODULE instance, LPCTSTR iniFile, LPCTSTR section, UINT id)
{
	WCHAR buffer[4096];
	CPUMeasure* measure = new CPUMeasure;
	measure->oldValue = 0;

	LPCTSTR data = ReadConfigString(section, L"CPUInclude", L"");
	if (data)
	{
		wcsncpy(buffer, data, 4096);
		buffer[4095] = 0;
		SplitName(buffer, measure->includes);
	}

	data = ReadConfigString(section, L"CPUExclude", L"");
	if (data)
	{
		wcsncpy(buffer, data, 4096);
		buffer[4095] = 0;
		SplitName(buffer, measure->excludes);
	}

	g_CPUMeasures[id] = measure;

	return 10000000;	// The values are 100 * 100000
}

/*
  This function is called when new value should be measured.
  The function returns the new value.
*/
UINT Update(UINT id)
{
	int value = 0;

	std::map<UINT, CPUMeasure*>::iterator i = g_CPUMeasures.find(id);
	if(i != g_CPUMeasures.end())
	{
		CPUMeasure* measure = (*i).second;

		if(measure)
		{
			// Check the platform
			OSVERSIONINFO osvi;
			ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
			osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
			if(GetVersionEx((OSVERSIONINFO*)&osvi) && osvi.dwPlatformId == VER_PLATFORM_WIN32_NT && osvi.dwMajorVersion > 4)
			{
				LONGLONG newValue = 0;
				ULONGLONG longvalue = 0;

				if (measure->includes.empty())
				{
					// First get the total CPU value
					longvalue = GetPerfData(L"Processor", L"_Total", L"% Processor Time");
					newValue = longvalue;


					// Then substract the excluded processes
					std::vector< std::wstring >::iterator j = measure->excludes.begin();
					for( ; j != measure->excludes.end(); j++)
					{
						longvalue = GetPerfData(L"Process", (*j).c_str(), L"% Processor Time");
						newValue += longvalue;		// Adding means actually substraction
					}

					// Compare with the old value
					if(measure->oldValue != 0) 
					{
						int val = 10000000 - (UINT)(newValue - measure->oldValue);
						if (val < 0) val = 0;
						value = val;
					}
					measure->oldValue = newValue;
				}
				else
				{
					// Add the included processes
					std::vector< std::wstring >::iterator j = measure->includes.begin();
					for( ; j != measure->includes.end(); j++)
					{
						longvalue = GetPerfData(L"Process", (*j).c_str(), L"% Processor Time");
						newValue += longvalue;
					}

					// Compare with the old value
					if(measure->oldValue != 0) 
					{
						value = (UINT)(newValue - measure->oldValue);
					}
					measure->oldValue = newValue;

				}

			}
			else
			{
				MessageBox(NULL, L"AdvancedCPU works only in Win2K/XP.", L"Rainmeter AdvancedCPU", MB_OK);
			}
		}
	}

	return value;
}

/*
  If the measure needs to free resources before quitting.
  The plugin can export Finalize function, which is called
  when Rainmeter quits (or refreshes).
*/
void Finalize(HMODULE instance, UINT id)
{
	// delete the measure
	std::map<UINT, CPUMeasure*>::iterator i = g_CPUMeasures.find(id);
	if(i != g_CPUMeasures.end())
	{
		delete (*i).second;
		g_CPUMeasures.erase(i);
	}

	CPerfSnapshot::CleanUp();
}

/*
  This method gets value of the given perfmon counter.
*/
ULONGLONG GetPerfData(PCTSTR ObjectName, PCTSTR InstanceName, PCTSTR CounterName)
{
	CPerfObject* pPerfObj;
	CPerfObjectInstance* pObjInst;
	CPerfCounter* pPerfCntr;
	BYTE data[256];
	WCHAR name[256];
	ULONGLONG value = 0;

	if(ObjectName == NULL || CounterName == NULL || wcslen(ObjectName) == 0 || wcslen(CounterName) == 0)
	{
		// Unable to continue
		return 0;
	}


	CPerfSnapshot snapshot(&g_CounterTitles);
	CPerfObjectList objList(&snapshot, &g_CounterTitles);

	if(snapshot.TakeSnapshot(ObjectName))
	{
		pPerfObj = objList.GetPerfObject(ObjectName);

		if(pPerfObj)
		{
			for(pObjInst = pPerfObj->GetFirstObjectInstance();
				pObjInst != NULL;
				pObjInst = pPerfObj->GetNextObjectInstance())
			{
				if (InstanceName != NULL && wcslen(InstanceName) > 0)
				{
					if(pObjInst->GetObjectInstanceName(name, 256))
					{
						if(_wcsicmp(InstanceName, name) != 0) 
						{
							delete pObjInst;
							continue;
						}
					}
					else
					{
						delete pObjInst;
						continue;
					}
				}

				pPerfCntr = pObjInst->GetCounterByName(CounterName);
				if(pPerfCntr != NULL)
				{
					pPerfCntr->GetData(data, 256, NULL);
					
					if(pPerfCntr->GetSize() == 1)
					{
						value = *(BYTE*)data;
					} 
					else if(pPerfCntr->GetSize() == 2)
					{
						value = *(WORD*)data;
					}
					else if(pPerfCntr->GetSize() == 4)
					{
						value = *(DWORD*)data;
					}
					else if(pPerfCntr->GetSize() == 8)
					{
						value = *(ULONGLONG*)data;
					}

					delete pPerfCntr;
					delete pObjInst;
					break;	// No need to continue
				}
				delete pObjInst;
			}
			delete pPerfObj;
		}
	}

	return value;
}

UINT GetPluginVersion()
{
	return 1003;
}

LPCTSTR GetPluginAuthor()
{
	return L"Rainy (rainy@iki.fi)";
}

