#ifdef _WIN32
#ifndef WIN32_LEAN_AND_MEAN
    #define WIN32_LEAN_AND_MEAN
#endif
#include <Windows.h>
#include <WinSock2.h>
typedef int socklen_t;
typedef unsigned long in_addr_t;
#else
    #define closesocket(sock) close(sock)

    #include <fcntl.h>
    #include <sys/socket.h>
    #include <sys/select.h>
    #include <netinet/tcp.h>
    #include <netinet/in.h>
    #include <arpa/inet.h>
    #include <unistd.h>

    typedef int SOCKET;
    #define INVALID_SOCKET -1
    #define SOCKET_ERROR -1
#endif

#include "lboot_udp.h"
#include "getopt.h"
#include <string.h>
#include <stdlib.h>


static int f_init(void);
static int f_cleanup(void);
static int f_parse_option(int opt);
static const char* f_get_err_str(int err);
static const char* f_get_opt_descr(void);
static int f_app_to_boot(int *out);

typedef enum {
    LBOOT_ERR_UDP_FIRST         = -12400,
    LBOOT_ERR_UDP_IP_ADDR       = -12400,
    LBOOT_ERR_UDP_PORT          = -12401,
    LBOOT_ERR_UDP_WSA_INIT      = -12402,
    LBOOT_ERR_UDP_SEND          = -12403,
    LBOOT_ERR_UDP_NO_APP_MSG    = -12404
} t_lboot_udp_errs;


static const char* f_err_str[] = {
    "invalid ip addr value",
    "invalid udp port value",
    "WSA init errror",
    "can't send udp packet",
    "udp message not specified"
};


/** Описание опций интерфейса  */
static const char* f_opt_descr =
"udp app-to-boot options:\n"\
"    --udp-app-ip-addr=addr  - board IP-addres (for instance \"192.168.0.1\")\n"\
"    --udp-app-port=port     - UDP port to send message\n"\
"    --udp-app-msg=msg       - message to send to application over UDP\n";


static struct sockaddr_in f_addr;
static const char *f_msg_ptr = NULL;


const t_app_iface g_udp_app_iface = {
    { "udp",
      "Message in UDP-packet",
      f_init,
      f_cleanup,
      f_parse_option,
      f_get_opt_descr,
      f_get_err_str,
    },
    f_app_to_boot
};


static int f_init(void) {
    int err = 0;
#ifdef _WIN32
    WORD wVersionRequested = MAKEWORD(2,2);
    WSADATA wsaData;

    if (WSAStartup(wVersionRequested, &wsaData))
        err = LBOOT_ERR_UDP_WSA_INIT;

    if (wsaData.wVersion!=wVersionRequested) {
        WSACleanup();
        err = LBOOT_ERR_UDP_WSA_INIT;
    }
#endif
    if (!err) {
        memset(&f_addr, 0, sizeof(f_addr));
        f_addr.sin_family = AF_INET;
        f_addr.sin_port = htons(69);
        f_addr.sin_addr.s_addr = htonl((192UL << 24) | (168UL << 16) | (0UL << 8) | (1));
    }
    return err;
}


static int f_cleanup(void) {
#ifdef _WIN32
    WSACleanup();
#endif
    return 0;
}

static int f_parse_option(int opt) {
    int err = 0;

    switch (opt) {
        case LBOOT_OPT_UDP_APP_IP_ADDR: {
                in_addr_t addr = inet_addr(optarg);
                if (addr==INADDR_NONE) {
                    err = LBOOT_ERR_UDP_IP_ADDR;
                } else {
                    f_addr.sin_addr.s_addr = addr;
                }
            }
            break;
        case LBOOT_OPT_UDP_APP_PORT: {
                int port = atoi(optarg);
                if ((port<=0) || (port>65535)) {
                    err = LBOOT_ERR_UDP_PORT;
                } else {
                    f_addr.sin_port = htons(port);
                }
            }
            break;
        case LBOOT_OPT_UDP_APP_MSG: {
                f_msg_ptr = optarg;
            }
            break;
        default:
            err = LBOOT_ERR_INVALID_OPTION;
            break;
    }
    return err;
}

static const char* f_get_err_str(int err) {
    return NULL;
}
static const char* f_get_opt_descr(void) {
    return f_opt_descr;
}



static int f_send_msg(SOCKET s, struct sockaddr_in* addr, const char* msg) {
    int err = 0;
    int len = strlen(msg);
    int trans;

    trans = sendto(s, msg, len, 0, (struct sockaddr*)addr, sizeof(struct sockaddr_in));
    if (trans != len) {
        err = LBOOT_ERR_UDP_SEND;
    }
    return err;
}


static int f_app_to_boot(int *out) {
    int err = f_msg_ptr == NULL ? LBOOT_ERR_UDP_NO_APP_MSG : 0;
    if (!err) {
        SOCKET s;
        s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
        if (s != INVALID_SOCKET) {
            err = f_send_msg(s, &f_addr, f_msg_ptr);
            closesocket(s);
        }
    } else {
        *out = 1;
    }
    return err;
}
