#include <cstdio>
#include <ctime>
#include <cstdarg>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <vector>
#include <cmath>

#define LOG_PATH "/home/pi/random-forest.log"
#define MAX_LOG_BYTES 524288

#define DEBUG_PRINT(fmt, ...) debug_printf(" [%s] " fmt, __func__, ##__VA_ARGS__)
void debug_printf(const char *fmt, ...)
{
	static int total = 0;
	int ret = 0;
	va_list ap;
	time_t now;
	struct tm *tm = NULL;
	FILE *fp = NULL;

	fp = fopen(LOG_PATH, "a+");
	if (!fp) return;

	time(&now);
	if ((tm=localtime(&now)) != NULL)
	{
		ret = fprintf(fp, "[%4d-%02d-%02d %02d:%02d:%02d]",
			(1900+tm->tm_year), (1+tm->tm_mon), tm->tm_mday,
			tm->tm_hour, tm->tm_min, tm->tm_sec);
		if (ret > 0) total += ret;
	}

	va_start(ap, fmt);
	ret = vfprintf(fp, fmt, ap);
	if (ret > 0) total += ret;
	va_end(ap);
	fclose(fp);

	if (total > MAX_LOG_BYTES)
	{
		struct stat sb;
		if (stat(LOG_PATH, &sb) || sb.st_size >= MAX_LOG_BYTES){
			unlink(LOG_PATH);
			total=0;
		}else{
			total = sb.st_size;
		}
	}
}

void measure_time(struct timeval *t) 
{
    if (!t)
        return;

    struct timeval start = *t, end;
    gettimeofday(&end, NULL);
    long elapsed_time = (end.tv_sec - start.tv_sec)*1000 + (end.tv_usec - start.tv_usec)/1000;
    printf("use_time: %ld ms\n", elapsed_time);
    *t = end;
}

bool isFeatureValid(const std::vector<float>& fea)
{
    for (float value : fea) {
        if (!std::isfinite(value) || std::abs(value) > 1e10f) {
            return false;
        }
    }

    return true;	
}

