 /* Simple C program that connects to MySQL Database server*/
#include <mysql/mysql.h>
//#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include "calculate.h"
#include "sendmysql.h"

void insertData(int node_id, float temperature, float humidity, int isoutside) {
    int pin = 0;
    MYSQL *conn;
    //MYSQL_RES *res;
    //MYSQL_ROW row;
    
    char *server = "localhost";
    char *user = "dhtuser";
    char *password = "raspberry"; /* set me first */
    char *database = "dhtstats";
    
    conn = mysql_init(NULL);
    
    /* Connect to database */
    if (!mysql_real_connect(conn, server, user, password, database, 0, NULL, 0)) {
        fprintf(stderr, "%s\n", mysql_error(conn));
        exit(1);
    }
    
    char *pquerystring = NULL;
    
    if (-1 == asprintf(&pquerystring, 
        "INSERT INTO stats (node_id, pin, humidity, temperature, isoutside, gm3) VALUES (%i, %i, %f, %f, %i, %f)", node_id, pin, humidity, temperature, isoutside, absoluteHumidityFloat(temperature, humidity))) {
        perror("asprintf() failed");
        } else {
            if (mysql_query(conn, pquerystring)) {
                fprintf(stderr, "%s\n", mysql_error(conn));
                free(pquerystring);
                exit(1);
            }
        }
        
        free(pquerystring);
        pquerystring = NULL;
        
        /* close connection */
        //mysql_free_result(res);
        mysql_close(conn);
}






void insertDataAverages(float temperature, float humidity, float gm3, int isoutside) {
   MYSQL *conn;
   //MYSQL_RES *res;
   //MYSQL_ROW row;

   char *server = "localhost";
   char *user = "dhtuser";
   char *password = "raspberry"; /* set me first */
   char *database = "dhtstats";

   conn = mysql_init(NULL);

   /* Connect to database */
   if (!mysql_real_connect(conn, server,
         user, password, database, 0, NULL, 0)) {
      fprintf(stderr, "%s\n", mysql_error(conn));
      exit(1);
   }
    
    /*
   // send SQL query 
   if (mysql_query(conn, "show tables")) {
      fprintf(stderr, "%s\n", mysql_error(conn));
      exit(1);
   }

   res = mysql_use_result(conn);

   // output table name 
   printf("MySQL Tables in mysql database:\n");
   while ((row = mysql_fetch_row(res)) != NULL)
      printf("%s \n", row[0]);
    */
   
    char *pquerystring = NULL;
    if (-1 == asprintf(&pquerystring, 
    "INSERT INTO average_stats (humidity, temperature, gm3, isoutside) VALUES (%f, %f, %f, %i)", humidity, temperature, absoluteHumidityFloat(temperature, humidity), isoutside)) {
        perror("asprintf() failed");
    } else {
        if (mysql_query(conn, pquerystring)) {
            fprintf(stderr, "%s\n", mysql_error(conn));
            free(pquerystring);
            exit(1);
        }
    }

    free(pquerystring);
    pquerystring = NULL;
    
   /* close connection */
   //mysql_free_result(res);
   mysql_close(conn);
}
