#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <syslog.h>
#include <stdarg.h>

#include "../../status.h"
#include "../../feeder.h"

#define __USE_GNU
/*
typedef struct measurement_t
{
	unsigned long unit_id;
	unsigned int sensor_id;
	time_t time;
	double value;
	struct measurement_t * next;
} measurement_t;

struct measurement_t * measurement_list;
*/

static void (*feederLog) (int priority, const char *fmt, ...);

int setLog(void *func)
{
    feederLog = func;
    return 0;
}

static FILE * f = NULL;

unsigned int timeout(void * lib_data, int sock, unsigned char * data)
{
    (void)lib_data;
    (void)sock;
    (void)data;

    f = fopen("mort_log.txt", "r");
    if (f == NULL)
    {
	feederLog(LOG_ERR, "mortlog: can not open input file (mort_log.txt)\n");
	return -1;
    }

    return 0;
}

int getval(char * line, const char * name, char * val)
{
    char * s, * se;

    s = strstr(line, name);
    s = strchr(s, ' ');
    s++;
    se = strchr(s, ',');
    memcpy(val, s, se - s);
    val[se-s] = 0;
    feederLog(LOG_DEBUG, "Value %s:%s\n", name, val);
    return 0;
}

unsigned int
process(void *lib_data, int sock, unsigned char *data,
        unsigned int length, unsigned long long int *id, time_t * tm,
        double *result_array, uint64_t * sensors, unsigned int *type)
{
    unsigned int res;
    static size_t len = 0;
    static char * line = NULL;
    ssize_t size;
    char name[256];

    (void)lib_data;
    (void)sock;
    (void)data;
    (void)length;

    feederLog(LOG_DEBUG, "mortlog: process\n");

    if (f == NULL)
    {
    	feederLog(LOG_ERR, "mortlog: file not opened\n");

	return -1;
    }
    while (size = getline(&line, &len, f), size >= 0)
    {
	if (strstr(line, "Saving sensor") != NULL)
	{
	    feederLog(LOG_DEBUG, "mortlog: %s\n", line);

	    getval(line, "id", name);
	    sensors[0] = atoi(name);

	    getval(line, "sensor", name);
	    feederLog(LOG_DEBUG, "mortlog: sensor %s\n", name);

	    
	    getval(line, "timestamp", name);
	    *tm = atoi(name);
	    getval(line, "value", name);
	    result_array[0] = atof(name);
	    getval(line, "device", name);
	    sensors[0] += (atoi(name) >> 8);
	    
	    *id = 105000000 + (atoi(name) & 0xFF);//todo: id must be configured by conf file, its not part of log file
	
	    
	//    feederLog(LOG_DEBUG, "mortlog: readline %f\n", result_array[0]);
	    *type = VALUES_TYPE_OBS;
	    
	    return 1;
	}
    }
    fclose(f);

    res = 0;
    return res;
}

int init(void *param)
{
    (void)param;

    feederLog(LOG_DEBUG, "mortlog: init\n");

    return 0;
}
