/**********************************************************************
 * LeechCraft - modular cross-platform feature rich internet client.
 * Copyright (C) 2006-2014  Georg Rudoy
 *
 * Boost Software License - Version 1.0 - August 17th, 2003
 *
 * Permission is hereby granted, free of charge, to any person or organization
 * obtaining a copy of the software and accompanying documentation covered by
 * this license (the "Software") to use, reproduce, display, distribute,
 * execute, and transmit the Software, and to prepare derivative works of the
 * Software, and to permit third-parties to whom the Software is furnished to
 * do so, all subject to the following:
 *
 * The copyright notices in the Software and this entire statement, including
 * the above license grant, this restriction and the following disclaimer,
 * must be included in all copies of the Software, in whole or in part, and
 * all derivative works of the Software, unless such copies or derivative
 * works are solely in the form of machine-executable object code generated by
 * a source language processor.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
 * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
 * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 **********************************************************************/

#include "linuxbackend.h"
#include <cmath>
#include <QFile>
#include <QtDebug>

namespace LeechCraft
{
namespace CpuLoad
{
	LinuxBackend::LinuxBackend (QObject *parent)
	: Backend { parent }
	{
	}

	namespace
	{
		Cummulative_t ReadProcStat ()
		{
			QFile file { "/proc/stat" };
			if (!file.open (QIODevice::ReadOnly))
			{
				qWarning () << Q_FUNC_INFO
						<< "cannot open"
						<< file.fileName ()
						<< file.errorString ();
				return {};
			}

			static const QByteArray cpuMarker { "cpu" };

			Cummulative_t result;

			for (const auto& line : file.readAll ().split ('\n'))
			{
				const auto& elems = line.split (' ');
				const auto& id = elems.value (0);
				if (!id.startsWith (cpuMarker))
					continue;

				bool ok = true;
				const auto cpuIdx = id.mid (cpuMarker.size ()).toInt (&ok);
				if (!ok)
					continue;

				QVector<long> cpuVec;
				for (const auto& elem : elems.mid (1))
				{
					bool ok = false;
					const auto num = elem.toLong (&ok);
					if (ok)
						cpuVec << num;
				}

				if (result.size () <= cpuIdx)
					result.resize (cpuIdx + 1);
				result [cpuIdx] = cpuVec;
			}

			return result;
		}
	}

	void LinuxBackend::Update ()
	{
		const int prevCpuCount = GetCpuCount ();

		auto savedLast = ReadProcStat ();
		std::swap (savedLast, LastCummulative_);

		const auto curCpuCount = GetCpuCount ();
		if (curCpuCount != prevCpuCount)
		{
			emit cpuCountChanged (curCpuCount);
			return;
		}

		Loads_.clear ();
		Loads_.resize (LastCummulative_.size ());

		for (int i = 0; i < curCpuCount; ++i)
		{
			auto& cpuLoad = Loads_ [i];

			auto lastCpuStats = LastCummulative_ [i];
			const auto& prevCpuStats = savedLast [i];
			for (int j = 0; j < lastCpuStats.size (); ++j)
				lastCpuStats [j] -= prevCpuStats [j];

			const auto total = lastCpuStats [0] + lastCpuStats [1] + lastCpuStats [2] + lastCpuStats [3] + lastCpuStats [4];

			auto setLoadPart = [&cpuLoad, total, &lastCpuStats, i] (int idx, LoadPriority prio) -> void
			{
				const auto& thisLoad = static_cast<double> (lastCpuStats [idx]) / total;
				cpuLoad [prio] = LoadTypeInfo { thisLoad };
			};

			setLoadPart (4, LoadPriority::IO);
			setLoadPart (1, LoadPriority::Low);
			setLoadPart (0, LoadPriority::Medium);
			setLoadPart (2, LoadPriority::High);
		}
	}

	int LinuxBackend::GetCpuCount () const
	{
		return LastCummulative_.size ();
	}

	QMap<LoadPriority, LoadTypeInfo> LinuxBackend::GetLoads (int cpu) const
	{
		return Loads_.value (cpu);
	}

}
}
