#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include "ip_connection.h"
#include "bricklet_gps_v2.h"

// #define HOST "192.168.1.6"
#define HOST "localhost"
#define PORT 4223
#define UID "CHk" // Change XYZ to the UID of your GPS Bricklet 2.0

volatile sig_atomic_t terminate = 0;
GPSV2 gps;

void sig_handler(int signo)
{
    if (signo == SIGINT) {
        printf("received SIGINT\n");
        terminate = 1;
    }
}

int main(void) {

    /* Register a signal handling function */
    if (signal(SIGINT, sig_handler) == SIG_ERR) {
        fprintf(stderr, "Can't catch SIGINT\n");
        abort();
    }

    // Create IP connection
    IPConnection ipcon;
    ipcon_create(&ipcon);

    // Create device object
    gps_v2_create(&gps, UID, &ipcon);

    // Connect to brickd
    if(ipcon_connect(&ipcon, HOST, PORT) < 0) {
        fprintf(stderr, "Could not connect\n");
        return 1;
    }

    bool ret_has_fix;
    uint8_t ret_satellites_view;
    int ret_latitude, ret_longitude;
    float latitude, longitude;
    char ret_ns, ret_ew;

    for (int i=0; i< 20; i++) {
        if (gps_v2_get_status(&gps, &ret_has_fix, &ret_satellites_view) <0) {
            fprintf(stderr, "Could not get status\n");
            return 1;
        }

        if (gps_v2_get_coordinates(&gps, &ret_latitude,
                                   &ret_ns, &ret_longitude, &ret_ew) < 0) {
            fprintf(stderr, "Could not get coordinates\n");
            return 1;
        }
        latitude = ret_latitude/1000000.0;
        longitude = ret_longitude/1000000.0;
        printf("Valid, latitude, longitude   = %d, %f, %f\n",
               ret_has_fix, latitude, longitude);

        usleep(1e6);
    }

    printf("Press key to exit\n");
    getchar();
    gps_v2_destroy(&gps);
    ipcon_destroy(&ipcon); // Calls ipcon_disconnect internally
    return 0;
}
