#include <mysql.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

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

int main(int argc, char** argv) {
    MYSQL *mysql_con = NULL;
    bool reconnect = 1;

    if (mysql_library_init(argc, argv, NULL)) {
        fprintf(stderr, "could not initialize MySQL client library\n");
        exit(1);
    }

    mysql_con = mysql_init(mysql_con);
  
    if (!mysql_con) {
        fprintf(stderr, "%s\n", "debug: could not initialize database");
        exit(1);
    }
    unsigned int mysql_ct;

    if (mysql_options(mysql_con, MYSQL_OPT_RECONNECT, &reconnect)) {
        fprintf(stderr, "mysql_options failed.");
    }

    if (mysql_real_connect(mysql_con,
                            "localhost",
                            "username", 
                            "password",
                            "dbname",
                            0,
                            "/var/run/mysqld/mysql.sock",
                            0) == NULL) {
        fprintf(stderr, "Failed to connect.\n");
        finish_with_error(mysql_con);
    }

    //Need a command here to MySQL
    if (mysql_query(mysql_con, "SELECT * FROM Events WHERE id=100;"))
    {
        finish_with_error(mysql_con);
    }

    MYSQL_RES *result = mysql_store_result(mysql_con);

    if (result == NULL)
    {
          finish_with_error(mysql_con);
    }

    MYSQL_ROW row = mysql_fetch_row(result);

    printf("%s\n", row[0]);

    mysql_free_result(result);


    printf("Waiting for 10s\n");
    sleep(10);


    //Need a commmand here to MySQL
    if (mysql_query(mysql_con, "SELECT * FROM Events WHERE id=200;"))
    {
        finish_with_error(mysql_con);
    }

    result = mysql_store_result(mysql_con);

    if (result == NULL)
    {
          finish_with_error(mysql_con);
    }

    row = mysql_fetch_row(result);

    printf("%s\n", row[0]);

    mysql_free_result(result);
    
    mysql_close(mysql_con);

    return 0;

}
