#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include <signal.h>
#include <unistd.h>

#include "sendmysql.h"
#include "calculate.h"

#define U_DISABLE_CURL
#define U_DISABLE_WEBSOCKET
#include <ulfius.h>

#define PORT 1337
#define PREFIX "/abshum"


struct _u_instance instance;


void exitFunction(void) {
    printf("Exiting HumidityServer.\n");
    ulfius_stop_framework(&instance);
    ulfius_clean_instance(&instance);
}

void sig_handler(int signo) {
    if (signo == SIGINT || signo == SIGTERM || signo == SIGKILL) {
        exit(0); //executes the exitFunction
    }
}

int callback_welcome (const struct _u_request * request, struct _u_response * response, void * user_data) {
    ulfius_set_string_body_response(response, 200, "Welcome to the HumidityPi rest service!");
    return U_CALLBACK_CONTINUE;
}




char * print_map(const struct _u_map * map) {
  char * line, * to_return = NULL;
  const char **keys, * value;
  int len, i;
  if (map != NULL) {
    keys = u_map_enum_keys(map);
    for (i=0; keys[i] != NULL; i++) {
      value = u_map_get(map, keys[i]);
      len = snprintf(NULL, 0, "key is %s, value is %s", keys[i], value);
      line = o_malloc((len+1)*sizeof(char));
      snprintf(line, (len+1), "key is %s, value is %s", keys[i], value);
      if (to_return != NULL) {
        len = strlen(to_return) + strlen(line) + 1;
        to_return = o_realloc(to_return, (len+1)*sizeof(char));
        if (strlen(to_return) > 0) {
          strcat(to_return, "\n");
        }
      } else {
        to_return = o_malloc((strlen(line) + 1)*sizeof(char));
        to_return[0] = 0;
      }
      strcat(to_return, line);
      o_free(line);
    }
    return to_return;
  } else {
    return NULL;
  }
}

char * read_file(const char * filename) {
  char * buffer = NULL;
  long length;
  FILE * f = fopen (filename, "rb");
  if (filename != NULL) {

    if (f) {
      fseek (f, 0, SEEK_END);
      length = ftell (f);
      fseek (f, 0, SEEK_SET);
      buffer = o_malloc (length + 1);
      if (buffer) {
        fread (buffer, 1, length, f);
      }
      buffer[length] = '\0';
      fclose (f);
    }
    return buffer;
  } else {
    return NULL;
  }
}

int callback_absTempHum(const struct _u_request *request, struct _u_response *response, void *user_data) {

    int i; 
    float temphum[2];
    const char **keys;
    keys = u_map_enum_keys(request->map_url);
    
    for (i = 0; i < 2; i++) {
        temphum[i] = atof(u_map_get(request->map_url, keys[i]));
    }
    char *response_body = msprintf("Temp: %f, Hum: %f, absHum: %f",temphum[0], temphum[1], absoluteHumidityFloat(temphum[0], temphum[1]));
    insertData(1, temphum[0], temphum[1], 0);
    
    ulfius_set_string_body_response(response, 200, response_body);
    //o_free(url_params);
    return U_CALLBACK_CONTINUE;
}




int main(void) {
    
    atexit(exitFunction);
    
    if (signal(SIGINT, sig_handler) == SIG_ERR) {
         printf("\ncan't catch SIGINT\n");
    }
    if (signal(SIGTERM, sig_handler) == SIG_ERR) {
         printf("\ncan't catch SIGTERM\n");
    }
    if (signal(SIGKILL, sig_handler) == SIG_ERR) {
         printf("\ncan't catch SIGTERM\n");
    }
    
    // Initialize instance with the port number
    if (ulfius_init_instance(&instance, PORT, NULL, NULL) != U_OK) {
        fprintf(stderr, "Error ulfius_init_instance, abort\n");
        return(1);
    }
    
    // Endpoint list declaration
    ulfius_add_endpoint_by_val(&instance, "GET", "/welcome", NULL, 0, &callback_welcome, NULL);
    ulfius_add_endpoint_by_val(&instance, "GET", PREFIX, "/:temp/:hum", 0, &callback_absTempHum, NULL);
    
    // Start the framework
    if (ulfius_start_framework(&instance) == U_OK) {
        printf("Start framework on port %d\n", instance.port);
        
        // Wait for a signal to stop the program.
        pause();
    } else {
        fprintf(stderr, "Error starting framework\n");
    }
    printf("End framework\n");
       
    return 0;
    
}
