/**********************************************************************
 * 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 "macbackend.h"
#include <algorithm>
#include <numeric>
#include <QtDebug>
#include <sys/sysctl.h>
#include <sys/types.h>
#include <mach/mach.h>
#include <mach/processor_info.h>
#include <mach/mach_host.h>

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

	void MacBackend::Update ()
	{
		UpdateCpuCount ();
		UpdateLoads ();
	}

	int MacBackend::GetCpuCount () const
	{
		return CpuCount_;
	}

	QMap<LoadPriority, LoadTypeInfo> MacBackend::GetLoads (int cpu) const
	{
		if (Loads_.size () != PrevLoads_.size () ||
				cpu >= Loads_.size ())
			return {};

		const auto& map = Loads_.at (cpu);
		const auto& prev = PrevLoads_.at (cpu);

		const auto sum = std::accumulate (map.begin (), map.end (), 0);
		const auto prevSum = std::accumulate (prev.begin (), prev.end (), 0);

		QMap<LoadPriority, LoadTypeInfo> result;
		for (auto i = map.begin (); i != map.end (); ++i)
		{
			if (i.key () == LoadPriority::Idle)
				continue;

			result [i.key ()] = LoadTypeInfo { (*i - prev [i.key ()]) / (sum - prevSum) };
		}

		return result;
	}

	void MacBackend::UpdateCpuCount ()
	{
		int mib[2] = { CTL_HW, HW_NCPU };
		auto size = sizeof (CpuCount_);
		if (sysctl (mib, 2, &CpuCount_, &size, nullptr, 0))
			CpuCount_ = 1;
	}

	void MacBackend::UpdateLoads ()
	{
		processor_info_array_t cpuInfo;
		mach_msg_type_number_t numCpuInfo;

		natural_t numCPUs = 0;
		const auto err = host_processor_info (mach_host_self (),
				PROCESSOR_CPU_LOAD_INFO, &numCPUs, &cpuInfo, &numCpuInfo);
		if (err != KERN_SUCCESS)
		{
			qWarning () << Q_FUNC_INFO
					<< "cannot get CPU info";
			return;
		}

		if (Loads_.size () == CpuCount_)
			std::swap (PrevLoads_, Loads_);

		Loads_.resize (CpuCount_);

		for (unsigned i = 0; i < CpuCount_; ++i)
		{
			auto& map = Loads_ [i];

			map [LoadPriority::IO] = 0;

			auto add = [&map, &cpuInfo, i] (LoadPriority prio, int id)
			{
				map [prio] = cpuInfo [i * CPU_STATE_MAX + id];
			};

			add (LoadPriority::High, CPU_STATE_SYSTEM);
			add (LoadPriority::Medium, CPU_STATE_USER);
			add (LoadPriority::Low, CPU_STATE_NICE);
			add (LoadPriority::Idle, CPU_STATE_IDLE);
		}
	}
}
}
