#include <time.h>
#include <stdio.h>
#include <string.h>
#include <dirent.h>
#include <errno.h>
#include "util.h"
#include "diot_util_error.h"

/* get monotonic number of seconds */
time_t get_monotonic_sec(void)
{
	struct timespec tv;
	clock_gettime(CLOCK_MONOTONIC, &tv);
	return tv.tv_sec;
}

char *get_file_content(char *filename, char *buff, size_t buff_size)
{
    FILE *file_h;
    int ret;

    file_h = fopen(filename, "r");
    if (!file_h) {
	diot_error_add("Unable to open file (%s)\n", filename);
	return "Error";
    }

    ret = fread(buff, 1, buff_size, file_h);

    if (ret >= buff_size)
	ret--;

    /* make sure the last character is 0 */
    buff[ret] = 0;

    if (ferror(file_h)) {
	diot_error_add("Error while reading file (%s)\n", filename);
	return "Error";
    }

    fclose(file_h);

    return buff;
}


int get_file_content_int(char *file_name, int *val)
{
    int ret;
    FILE * fp;

    fp = fopen (file_name, "r");
    if (!fp) {
	diot_error_add("Unable to read file %s\n", file_name);
	return -1;
    }

    ret = fscanf(fp, "%d", val);
    fclose(fp);
    if (ret <= 0 || ret == EOF) {
	diot_error_add("Unable to read value from file %s\n", file_name);
	return -1;
    }

    return ret;
}

int set_file_content_int(char *file_name, int val)
{
    int ret;
    FILE * fp;

    fp = fopen (file_name, "w");
    if (!fp) {
	diot_error_add("Unable to write to file %s\n", file_name);
	return -1;
    }

    ret = fprintf(fp, "%d", val);
    fclose(fp);
    if (ret <= 0 || ret == EOF) {
	diot_error_add("Unable to write value %ld to file %s\n",
		       val, file_name);
	return -1;
    }

    return ret;
}

char *end_str_at_newline(char *buff)
{
    char *p;

    p = strchr(buff, '\n');
    if (p)
	*p = '\0';

    return buff;
}

char *string_map_get(char *name, struct string_map *map, size_t map_size)
{
    int i;

    for (i = 0; i < map_size; i++)
    if (!strcmp(map[i].index, name))
        return map[i].label;

    return "Unknown";
}

char *get_hwmon_number(char *hwmon_sys_dir, char * buff, size_t buff_size)
{
    int ret;
    DIR *d;
    struct dirent *dir;

    d = opendir(hwmon_sys_dir);
    if (!d) {
	return NULL;
    }

    while ((dir = readdir(d)) != NULL) {
	if (!strncmp(dir->d_name, ".", 1))
	    continue;
	ret = snprintf(buff, buff_size, "%s", dir->d_name);
	if (ret > buff_size) {
	    /* buffer not big enough */
	    diot_error_add("Buffer too short for hwmon number. Written "
			   "\"%s\"(len %d), wanted \"%s\"(len %d)\n",
			   buff, strlen(buff), dir->d_name, strlen(dir->d_name)
			  );
	    closedir(d);
	    errno = ENOBUFS;
	    return NULL;
	}
	/* assume there is only one entry in the directory like:
	 * /sys/devices/platform/amba/ff030000.i2c/i2c-1/i2c-9/9-0012/hwmon
	 */
	break;
    }
    closedir(d);

    return buff;
}
