
#include "fbdata.h"


void finish_with_error(MYSQL *con) {
  fprintf(stderr, "%s\n", mysql_error(con));
  mysql_close(con);
  exit(1);
}


void updateData(sourcedata data[]) {

	// query database for latest values
    char query[] = "\
SELECT time, source, metric, value \
FROM readings AS r \
INNER JOIN (SELECT MAX(time) AS maxtime, source_id, metric_id FROM readings GROUP BY source_id,metric_id) AS mr \
    ON mr.maxtime = r.time AND mr.source_id = r.source_id AND mr.metric_id = r.metric_id \
INNER JOIN sources AS s \
    ON r.source_id = s.id \
INNER JOIN metrics AS m \
    ON r.metric_id = m.id;\
";


    printf("Connecting to database ...\n");
    printf("MySQL client version: %s\n", mysql_get_client_info());
	
    MYSQL *con;
	if (!(con = mysql_init(NULL))) finish_with_error(con); 
    if (!mysql_real_connect(con, "web-pi", "grafanaReader", "grafanaReader", "grafanaData", 0, NULL, 0)) finish_with_error(con);
    
    //printf("%s\n",query);
    printf("Running query ...\n");
    //printf("Query: %s\n", query);
	if (mysql_query(con, query)) finish_with_error(con);
    printf("Finished.\n");
	
    MYSQL_RES *result; 
    if (!(result = mysql_store_result(con))) finish_with_error(con);
	int num_fields = mysql_num_fields(result);
  	if (num_fields > 3) { // sanity check to honor bounds
        MYSQL_ROW row;
        while ((row = mysql_fetch_row(result))) {
            unsigned long *length = mysql_fetch_lengths (result); // only valid for current row
            int l = *(length + 3) - 2;
            //printf("%s [l = %d]\n", row[3], l);

            // data binding
            for (int i = 0; i < 4; i++) {
                if (strcmp(row[1], data[i].text) == 0) {
                    if (strcmp(row[2], "Temperatur") == 0 && data[i].temperature == NULL) {
                        data[i].temperature = calloc((l + 1),sizeof(char)); // +1 for null-termination
                        memcpy(data[i].temperature, row[3], l * sizeof(char));
                    }
                    else if (strcmp(row[2], "Luftfeuchte") == 0 && data[i].humidity == NULL){
                        data[i].humidity = calloc((l + 1),sizeof(char)); // +1 for null-termination
                        memcpy(data[i].humidity, row[3], l * sizeof(char));
                    }
                }
            }

            // debugging
            //for(int i = 0; i < num_fields; i++) printf("%s ", row[i] ? row[i] : "NULL");
            //printf("\n");
        }
    }
    // free memory after dashboard was updated
  	mysql_free_result(result);
	mysql_close(con);
    printf("Done!\n");
}

