/* Drives Kneedeck from C or C++ on Windows, on the same PC:

       #include "kneedeck.h"
       kneedeck_send("{\"tab\": \"Carte LFXX\", \"page\": 3}");

   A message is a JSON text in UTF-8: one object, or a list of them. Kneedeck listens on this PC only, on
   port 47831, and answers nothing. Link with ws2_32 (Visual Studio: #pragma comment below). */
#ifndef KNEEDECK_H
#define KNEEDECK_H

#include <string.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#ifdef _MSC_VER
#pragma comment(lib, "ws2_32")
#endif

#define KNEEDECK_PORT 47831

/* 0 when sent, -1 otherwise. */
static int kneedeck_send(const char *json) {
    WSADATA wsa;
    if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) return -1;
    SOCKET sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if (sock == INVALID_SOCKET) {
        WSACleanup();
        return -1;
    }
    struct sockaddr_in to;
    memset(&to, 0, sizeof to);
    to.sin_family = AF_INET;
    to.sin_port = htons(KNEEDECK_PORT);
    to.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
    int sent = sendto(sock, json, (int)strlen(json), 0, (struct sockaddr *)&to, sizeof to);
    closesocket(sock);
    WSACleanup();
    return sent == SOCKET_ERROR ? -1 : 0;
}

#endif
