/*
 * Sentinella
 * http://sentinella.sourceforge.net/
 * Copyright (c) 2009-2011 Carlos Olmedo Escobar <carlos.olmedo.e@gmail.com>
 *
 * 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.
 */

#include "CPU.h"

CPU::CPU(const qint64 msecsLimit, const qint64 interval, const int percentageLimit,
		const bool bigger) :
	AbstractLoopCondition(msecsLimit, interval), percentageLimit(percentageLimit), bigger(bigger),
			cpus(NULL) {
#ifdef SA_OPEN_CPU
	if ((error = sa_open_cpu()) != 0)
		return;
#endif
	if ((error = sa_count_cpus(&numberOfCPUs)) != 0)
		return;
	cpus = (struct sa_cpu*) calloc(numberOfCPUs, sizeof(struct sa_cpu));
	if (cpus == NULL) {
		error = ENOMEM;
		return;
	}
	evaluate();
}

CPU::~CPU() {
#ifdef SA_CLOSE_CPU
	sa_close_cpu();
#endif
	if (cpus != NULL)
		free(cpus);
}

bool CPU::evaluate() {
	if ((error = sa_reset_cpus()) != 0)
		return 0;

	uint16_t writtenCPUs;
	if ((error = sa_get_cpus(cpus, numberOfCPUs, &writtenCPUs)) != 0)
		return 0;

	float average = 0;
	for (uint16_t i = 0; i < writtenCPUs; ++i)
		average += cpus[i].idle;
	average /= writtenCPUs;
	average = 100.0 - average;

	return (bigger ? average > percentageLimit : average < percentageLimit);
}
