#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sensors.h>

#include "temp.h"

static FILE *f = NULL;
static char sensors = 0;

static const sensors_chip_name *chip_name = NULL;
static const sensors_feature_data *feature;

char *cpu_feature_name = "temp1";
char *sys_feature_name = "temp2";

temperature_t t_type = CELCIUS;

static int cpu_feature = 0;
static int sys_feature = 0;

void temp_deinit() {
	if (f != NULL) {
		fclose(f);
	}

	if (sensors) {
		sensors_cleanup();
	}
}

void temp_init(const char *filename) {
	const sensors_chip_name *name;
	int chip_nr = 0, f1, f2;
	
	atexit(temp_deinit);

	f = fopen(filename, "r");
	if (f == NULL) {
		fprintf(stderr, "could not open configfile %s: %s\n", filename,
				strerror(errno));
		exit(1);
	}

	if (sensors_init(f)) {
		fprintf(stderr, "could not initialize sensors\n");
		exit(1);
	}

	sensors = 1;

	while ((name = sensors_get_detected_chips(&chip_nr)) != NULL &&
			chip_name == NULL) {
		f1 = f2 = 0;

		while ((feature = sensors_get_all_features(*name, &f1, &f2)) != NULL) {
			if (sensors_get_ignored(*name, feature->number) != 0) {
				if (strcmp(feature->name, cpu_feature_name) == 0) {
					cpu_feature = feature->number;
					chip_name = name;
				} else if (strcmp(feature->name, sys_feature_name) == 0) {
					sys_feature = feature->number;
					chip_name = name;
				}
			}
		}
	}

	if (chip_name == NULL) {
		fprintf(stderr, "could not find a suitable chip\n");
		exit(1);
	}
}

void temp_getusage(unsigned int *cpu_temp, unsigned int *sys_temp) {
	double cpu, sys;

	sensors_get_feature(*chip_name, cpu_feature, &cpu);
	sensors_get_feature(*chip_name, sys_feature, &sys);

	if (t_type == FAHRENHEIT) {
		cpu = TO_FAHRENHEIT(cpu);
		sys = TO_FAHRENHEIT(sys);
	} else if (t_type == KELVIN) {
		cpu = TO_KELVIN(cpu);
		sys = TO_KELVIN(sys);
	}
	
	*cpu_temp = (unsigned int)(cpu);
	*sys_temp = (unsigned int)(sys);
}
