#include "iec_include.h"
#include "lwip/opt.h"
#include "lwip/def.h"
#include "lwip/ip_addr.h"
#include "lwip/dns.h"
#include "lwip/netdb.h"
#include "lwip/sockets.h"
#include "lwip/sys.h"
#include "lwip/netif.h"

#include <string.h>
#include <stdlib.h>

#define _GNU_SOURCE
#define INET6_ADDRSTRLEN 65

#ifndef DEBUG_SOCKET
#define DEBUG_SOCKET 0
#endif

#define nfds_t 			unsigned int
#define POLLIN 			0x0001  //表示有数据可读
#define POLLPRI 		0x0002  //表示有紧急数据可读
#define POLLOUT 		0x0004  //表示数据可写
#define POLLERR 		0x0008  //指定描述符发生错误
#define POLLHUP 		0x0010  //指定文件描述符挂起事件
#define POLLNVAL 		0x0020  //指定描述符非法
  
#define POLLRDNORM 	0x0040  //表示有普通数据可读
#define POLLRDBAND 	0x0080  //表示有优先数据可读
#define POLLWRNORM 	0x0100  //表示普通数据可写
#define POLLWRBAND 	0x0200  //表示优先数据可写
#define POLLMSG 		0x0400  //消息可用（注意：这个常量在标准poll()函数定义中并不存在，可能是特定环境或扩展中的定义）
#define POLLREMOVE 	0x1000  
#define POLLRDHUP 	0x2000  

typedef struct sMessageQueue* MessageQueue;

struct sServerSocket {
    int fd;
    int backLog;
};

struct sUdpSocket {
    int fd;
};

struct pollfd{
	int fd; // 文件描述符
	short int events; // 注册的事件
	short int revents; // 实际发生的事件，由内核填充
};

static int mypoll(struct pollfd *fds, nfds_t nfds, int timeout) {
    fd_set readfds, writefds, errfds;
    struct timeval tv;
    int i, ret;

    FD_ZERO(&readfds);
    FD_ZERO(&writefds);
    FD_ZERO(&errfds);

    for (i = 0; i < nfds; i++) {
        if (fds[i].events & POLLIN) {
            FD_SET(fds[i].fd, &readfds);
        }
        if (fds[i].events & POLLOUT) {
            FD_SET(fds[i].fd, &writefds);
        }
        FD_SET(fds[i].fd, &errfds);
    }

    if (timeout >= 0) {
        tv.tv_sec = timeout / 1000;
        tv.tv_usec = (timeout % 1000) * 1000;
    }

    ret = select(nfds, &readfds, &writefds, &errfds, (timeout >= 0) ? &tv : NULL);
    if (ret < 0) {
        return -1; // error
    }

    for (i = 0; i < nfds; i++) {
        fds[i].revents = 0;
        if (FD_ISSET(fds[i].fd, &readfds)) {
            fds[i].revents |= POLLIN;
        }
        if (FD_ISSET(fds[i].fd, &writefds)) {
            fds[i].revents |= POLLOUT;
        }
        if (FD_ISSET(fds[i].fd, &errfds)) {
            fds[i].revents |= POLLERR;
        }
    }

    return ret; // number of descriptors with events or 0 for timeout
}

int
Socket_read(Socket self, uint8_t* buf, int size)
{
    if (self->fd == -1)
        return -1;

    int read_bytes = recv(self->fd, buf, size, MSG_DONTWAIT);

    if (read_bytes == 0)
        return -1;

    if (read_bytes == -1) {
        int error = errno;

        switch (error) {

            case EAGAIN:
                return 0;
            case EBADF:
                return -1;

            default:

                if (DEBUG_SOCKET)
                    printf("DEBUG_SOCKET: recv returned error (errno=%i)\n", error);

                return -1;
        }
    }

    return read_bytes;
}
int
Socket_write(Socket self, uint8_t* buf, int size)
{
    if (self->fd == -1)
        return -1;

    /* MSG_NOSIGNAL - prevent send to signal SIGPIPE when peer unexpectedly closed the socket */
    int retVal = send(self->fd, buf, size, 0);

    if (retVal == -1) {
        if (errno == EAGAIN) {
            return 0;
        }
        else {
            if (DEBUG_SOCKET)
                printf("DEBUG_SOCKET: send returned error (errno=%i)\n", errno);
        }
    }

    return retVal;
}

char*
Socket_getPeerAddressStatic(Socket self, char* peerAddressString)
{
    struct sockaddr_storage addr;
    socklen_t addrLen = sizeof(addr);
    memset(&addr, 0, sizeof(addr));

    if (getpeername(self->fd, (struct sockaddr*) &addr, &addrLen) == -1)
    {
        if (DEBUG_SOCKET)
            printf("DEBUG_SOCKET: getpeername -> errno: %i\n", errno);

        return NULL;
    }

    char addrString[INET6_ADDRSTRLEN + 7];
    int port;

    bool isIPv6;

    if (addr.ss_family == AF_INET) {
        struct sockaddr_in* ipv4Addr = (struct sockaddr_in*) &addr;
        port = ntohs(ipv4Addr->sin_port);
        inet_ntop(AF_INET, &(ipv4Addr->sin_addr), addrString, INET_ADDRSTRLEN);
        isIPv6 = false;
    }
//    else if (addr.ss_family == AF_INET6) {
//        struct sockaddr_in6* ipv6Addr = (struct sockaddr_in6*) &addr;
//        port = ntohs(ipv6Addr->sin6_port);
//        inet_ntop(AF_INET6, &(ipv6Addr->sin6_addr), addrString, INET6_ADDRSTRLEN);
//        isIPv6 = true;
//    }
    else
        return NULL;

    if (isIPv6)
        sprintf(peerAddressString, "[%s]:%i", addrString, port);
    else
        sprintf(peerAddressString, "%s:%i", addrString, port);

    return peerAddressString;
}

static void
closeAndShutdownSocket(int socketFd)
{
    if (socketFd != -1) {

        if (DEBUG_SOCKET)
            printf("SOCKET: call shutdown for %i!\n", socketFd);

        /* shutdown is required to unblock read or accept in another thread! */
        int result = shutdown(socketFd, SHUT_RDWR);

        if (result == -1) {
            if (DEBUG_SOCKET)
                printf("SOCKET: shutdown error: %i\n", errno);
        }

        result = close(socketFd);

        if (result == -1) {
            if (DEBUG_SOCKET)
                printf("SOCKET: close error: %i\n", errno);
        }
    }
}

int
Handleset_waitReady(HandleSet self, unsigned int timeoutMs)
{
    /* check if pollfd array is updated */
    if (self->pollfdIsUpdated == false) {
        if (self->fds) {
            GLOBAL_FREEMEM(self->fds);
            self->fds = NULL;
        }

        self->nfds = LinkedList_size(self->sockets);

        self->fds = GLOBAL_CALLOC(self->nfds, sizeof(struct pollfd));

        int i;

        for (i = 0; i < self->nfds; i++) {
            LinkedList sockElem = LinkedList_get(self->sockets, i);

            if (sockElem) {
                Socket sock = (Socket) LinkedList_getData(sockElem);

                if (sock) {
                    self->fds[i].fd = sock->fd;
                    self->fds[i].events = POLLIN;
                }
            }
        }

        self->pollfdIsUpdated = true;
    }

    if (self->fds && self->nfds > 0) {
        int result = mypoll(self->fds, self->nfds, timeoutMs);

        if (result == -1 && errno == EINTR) {
            result = 0;
        }

        if (result == -1) {
            if (DEBUG_SOCKET)
                printf("SOCKET: poll error (errno: %i)\n", errno);
        }

        return result;
    }
    else {
        /* there is no socket to wait for */
        return 0;
    }
}
void
Socket_destroy(Socket self)
{
    int fd = self->fd;

    self->fd = -1;

    closeAndShutdownSocket(fd);

    delay_ms(10);

    GLOBAL_FREEMEM(self);
}

HandleSet
Handleset_new(void)
{
   HandleSet self = (HandleSet) GLOBAL_MALLOC(sizeof(struct sHandleSet));

   if (self) {
       self->sockets = LinkedList_create();
       self->pollfdIsUpdated = false;
       self->fds = NULL;
       self->nfds = 0;
   }

   return self;
}
void
ServerSocket_destroy(ServerSocket self)
{
    int fd = self->fd;

    self->fd = -1;

    closeAndShutdownSocket(fd);

    delay_ms(10);

    GLOBAL_FREEMEM(self);
}

void
Handleset_destroy(HandleSet self)
{
    if (self) {
        if (self->sockets)
            LinkedList_destroyStatic(self->sockets);

        if (self->fds)
            GLOBAL_FREEMEM(self->fds);

        GLOBAL_FREEMEM(self);
    }
}

static bool
prepareAddress(const char* address, int port, struct sockaddr_in* sockaddr)
{
    bool retVal = true;

    memset((char *) sockaddr, 0, sizeof(struct sockaddr_in));

    if (address != NULL) {
        struct addrinfo addressHints;
        struct addrinfo *lookupResult;
        int result;

        memset(&addressHints, 0, sizeof(struct addrinfo));
        addressHints.ai_family = AF_INET;
        result = getaddrinfo(address, NULL, &addressHints, &lookupResult);

        if (result != 0) {

            if (DEBUG_SOCKET)
                printf("SOCKET: getaddrinfo failed (code=%i)\n", result);

            retVal = false;
            goto exit_function;
        }

        memcpy(sockaddr, lookupResult->ai_addr, sizeof(struct sockaddr_in));
        freeaddrinfo(lookupResult);
    }
    else
        sockaddr->sin_addr.s_addr = htonl(INADDR_ANY);

    sockaddr->sin_family = AF_INET;

    if (port < 0)
        port = 0;

    sockaddr->sin_port = htons(port);

exit_function:
    return retVal;
}

static void
setSocketNonBlocking(Socket self)
{
    int flags = fcntl(self->fd, F_GETFL, 0);
    fcntl(self->fd, F_SETFL, flags | O_NONBLOCK);
}


ServerSocket
TcpServerSocket_create(const char* address, int port)
{
    ServerSocket serverSocket = NULL;

    int fd;

    if ((fd = socket(AF_INET, SOCK_STREAM, 0)) >= 0) {
        struct sockaddr_in serverAddress;

        if (!prepareAddress(address, port, &serverAddress)) {
            close(fd);
            return NULL;
        }

        int optionReuseAddr = 1;
        setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *) &optionReuseAddr, sizeof(int));

#if 0//LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 37)
        int tcpUserTimeout = 10000;
        int result = setsockopt(fd, SOL_TCP,  TCP_USER_TIMEOUT, &tcpUserTimeout, sizeof(tcpUserTimeout));

        if (result < 0) {
            if (DEBUG_SOCKET)
                printf("SOCKET: failed to set TCP_USER_TIMEOUT\n");
        }
#else
#warning "TCP_USER_TIMEOUT not supported by linux kernel"
#endif

        if (bind(fd, (struct sockaddr *) &serverAddress, sizeof(serverAddress)) >= 0) {
            serverSocket = (ServerSocket) GLOBAL_MALLOC(sizeof(struct sServerSocket));
            serverSocket->fd = fd;
            serverSocket->backLog = 2;

            setSocketNonBlocking((Socket) serverSocket);
        }
        else {
            close(fd);
            return NULL ;
        }
    }

    return serverSocket;
}

void
ServerSocket_listen(ServerSocket self)
{
    if (listen(self->fd, self->backLog) == -1) {
        if (DEBUG_SOCKET)
            printf("SOCKET: listen failed (errno: %i)\n", errno);
    }
}

static void
activateTcpNoDelay(Socket self)
{
    /* activate TCP_NODELAY option - packets will be sent immediately */
    int flag = 1;
    setsockopt(self->fd, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int));
}

/* CHANGED TO MAKE NON-BLOCKING --> RETURNS NULL IF NO CONNECTION IS PENDING */
Socket
ServerSocket_accept(ServerSocket self)
{
    int fd;

    Socket conSocket = NULL;

    fd = accept(self->fd, NULL, NULL );

    if (fd >= 0) {
        conSocket = (Socket) GLOBAL_CALLOC(1, sizeof(struct sSocket));

        if (conSocket) {
            conSocket->fd = fd;

            setSocketNonBlocking(conSocket);

            activateTcpNoDelay(conSocket);
        }
        else {
            /* out of memory */
            close(fd);

            if (DEBUG_SOCKET)
                printf("SOCKET: out of memory\n");
        }
    }
    else {
        if (DEBUG_SOCKET)
            printf("SOCKET: accept failed (errno=%i)\n", errno);
    }

    return conSocket;
}
