#include <semaphore.h>
#include <signal.h>
#include <pthread.h>
#include "http-server.h"
#include "rssi_list.h"

extern volatile sig_atomic_t got_sigint;
extern Element * rssi_list;
extern sem_t synchro;

/* Starts the MicroHTTP deamon.
*
* Input: None.
* Output: 0 if success, -1 otherwise.
*/
int start_microhttpd(void) {
    struct MHD_Daemon *daemon;
    printf("[+] MicroHTTP daemon: creation.\n");
    daemon = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY, PORT, NULL, NULL, &connection_callback, NULL, MHD_OPTION_END);

    /* The deamon could not be created. */
    if (!daemon) {
        perror("[@] MicroHTTP daemon: creation error.");
        return -1;
    }


    printf("[+] MicroHTTP daemon: creation success.\n");
    /* HACK: Avoid the daemon to complete. */
    getchar();


    MHD_stop_daemon(daemon);
    printf("[+] MicroHTTP daemon: stopped.\n");
    return 0;
}

/* Callback function which is triggered when a new connection is created in the
* MicroHTTP daemon.
*/
int connection_callback(void *cls,
                        struct MHD_Connection *connection,
                        const char *url,
                        const char *method,
                        const char *version,
                        const char *upload_data,
                        size_t *upload_data_size,
                        void **con_cls) {
    
        struct MHD_Response *response;

	const char *res;
	printf("\n Connection on httpd received \n");
	if (0 == strcmp (url,"/RSSIRequest")) {
		printf("\n Request \n");
	 	res= "{ \"ss\" : 42 }";
	}
	else{
		res = "Don't know what you want : /RSSIRequest available";
	}
	response = MHD_create_response_from_buffer (strlen (res), (void *) res,MHD_RESPMEM_PERSISTENT);
	int  callback = MHD_queue_response (connection, MHD_HTTP_OK, response);
	MHD_destroy_response (response);
	return callback; 
}
