/*******************************************************************************
Copyright (c) 2014, Jan Koester jan.koester@gmx.net
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the <organization> nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************/

#include "socket.h"
#include "exception.h"
#include <ws2tcpip.h>
#include <cstring>

namespace netplus {

udp::udp() : socket() {
    _Socket = INVALID_SOCKET;
    _Type = sockettype::UDP;
}

udp::udp(SOCKET sock) : socket() {
    _Socket = sock;
    _Type = sockettype::UDP;
}

udp::~udp() {
    if (_Socket != INVALID_SOCKET)
        socket::close();
}

udp::udp(const std::string& addr, int port, int maxconnections, int sockopts)
: socket() {
    _Maxconnections = maxconnections;
    _Type = sockettype::UDP;

    addrinfo hints{};
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_DGRAM;
    hints.ai_flags = AI_PASSIVE;

    addrinfo* result = nullptr;
    char serv[32];
    std::snprintf(serv, sizeof(serv), "%d", port);

    int gai = ::getaddrinfo(addr.empty() ? nullptr : addr.c_str(), serv, &hints, &result);
    if (gai != 0) {
        NetException e;
        e[NetException::Critical] << "udp getaddrinfo failed";
        throw e;
    }

    for (addrinfo* rp = result; rp; rp = rp->ai_next) {
        _Socket = ::WSASocketA(rp->ai_family, rp->ai_socktype, rp->ai_protocol, nullptr, 0, WSA_FLAG_OVERLAPPED);
        if (_Socket == INVALID_SOCKET)
            continue;

        setAddrFromAI(rp);
        break;
    }

    ::freeaddrinfo(result);

    if (_Socket == INVALID_SOCKET) {
        NetException e;
        e[NetException::Critical] << "Failed to create UDP socket";
        throw e;
    }

    BOOL opt = TRUE;
    ::setsockopt(_Socket, SOL_SOCKET, SO_REUSEADDR, (const char*)&opt, sizeof(opt));
}

udp::udp(const std::string& uxsocket, int maxconnections, int sockopts)
: socket() {
    NetException e;
    e[NetException::Critical] << "Unix domain sockets unsupported on Windows";
    throw e;
}

void udp::bind() {
    if (::bind(_Socket, reinterpret_cast<sockaddr*>(&_Addr), _AddrLen) == SOCKET_ERROR) {
        NetException e;
        e[NetException::Error] << "udp::bind failed";
        throw e;
    }
}

void udp::listen() {
    // UDP no listen
}

void udp::setNonBlock() {
    u_long mode = 1;
    ::ioctlsocket(_Socket, FIONBIO, &mode);
}

int udp::getMaxconnections() {
    return _Maxconnections;
}

udp& udp::operator=(SOCKET sock) {
    _Socket = sock;
    return *this;
}

void udp::accept(std::unique_ptr<socket>& csock, bool nonblock) {
    // UDP accept no-op
    (void)csock;
    (void)nonblock;
}

size_t udp::sendData(buffer& data, int flags) {
    size_t sendlen = data.size;

    if (!_SendBuffer) {
        _SendBuffer = std::make_unique<buffer>(sendlen);
    }
    if (_SendBuffer->size < sendlen) {
        _SendBuffer = std::make_unique<buffer>(sendlen);
    }

    std::memcpy(_SendBuffer->data.buf, data.data.buf, sendlen);
    _SendBuffer->data.len = (ULONG)sendlen;
    std::memset(&_SendBuffer->overlapped, 0, sizeof(WSAOVERLAPPED));
    _SendBuffer->operation = OP_WRITE;

    _pendingIocpWrite.store(true);

    DWORD bytesSent = 0;
    int ret = ::WSASend(_Socket, &_SendBuffer->data, 1, &bytesSent, flags,
                        &_SendBuffer->overlapped, nullptr);

    if (ret == SOCKET_ERROR) {
        int err = ::WSAGetLastError();
        if (err == WSA_IO_PENDING) {
            return sendlen;
        }
        _pendingIocpWrite.store(false);
        NetException e;
        e[NetException::Error] << "udp::sendData WSASend failed: " << err;
        throw e;
    }

    return sendlen;
}

size_t udp::sendTo(buffer& data, int flags) {
    const char* p = data.data.buf;
    int s = ::sendto(_Socket, p, (int)data.size, flags,
                     reinterpret_cast<const sockaddr*>(&_Addr), _AddrLen);

    if (s == SOCKET_ERROR) {
        int err = ::WSAGetLastError();
        if (err == WSAEWOULDBLOCK) {
            NetException e;
            e[NetException::Note] << "udp::sendTo would block";
            throw e;
        }
        NetException e;
        e[NetException::Error] << "udp::sendTo WSASendTo failed: " << err;
        throw e;
    }

    return (size_t)s;
}

size_t udp::recvData(buffer& data, int flags) {
    if (_ReadBuffer && _ReadBuffer->overlapped.InternalHigh > 0) {
        size_t r = (size_t)_ReadBuffer->overlapped.InternalHigh;
        if (r > data.size)
            r = data.size;
        std::copy(_ReadBuffer->data.buf, _ReadBuffer->data.buf + r, data.data.buf);
        _ReadBuffer->overlapped.InternalHigh = 0;
        return r;
    }

    sockaddr_storage peer{};
    int peerLen = sizeof(peer);

    int r = ::recvfrom(_Socket, data.data.buf, (int)data.size, flags,
        reinterpret_cast<sockaddr*>(&peer), &peerLen);

    if (r == SOCKET_ERROR) {
        int err = ::WSAGetLastError();
        if (err == WSAEWOULDBLOCK) {
            NetException e;
            e[NetException::Note] << "udp::recvData: EAGAIN/WSAEWOULDBLOCK";
            throw e;
        }
        return 0; // or throw error?
    }

    if (r > 0) {
        data.size = (size_t)r;
        return (size_t)r;
    }
    return 0;
}

void udp::setBlock() {
    u_long mode = 0;
    if (::ioctlsocket(_Socket, FIONBIO, &mode) == SOCKET_ERROR) {
        NetException e;
        e[NetException::Error] << "udp::setBlock failed";
        throw e;
    }
}

void udp::accept(LPFN_ACCEPTEX lpfnAcceptEx, std::unique_ptr<socket>& csock) {
    // UDP does not use AcceptEx - this is a no-op
    (void)lpfnAcceptEx;
    (void)csock;
}

void udp::flush_out() {
    // Empty - udp::sendData() handles async WSASend with _pendingIocpWrite
}

void udp::prime_read() {
    DWORD bytesRecv = 0;
    DWORD dwFlags = 0;

    if (!_ReadBuffer)
        _ReadBuffer.reset(new buffer);

    std::memset(&_ReadBuffer->overlapped, 0, sizeof(WSAOVERLAPPED));
    _ReadBuffer->operation = OP_READ;

    int ret = ::WSARecv(_Socket, &_ReadBuffer->data, 1, &bytesRecv, &dwFlags,
        &_ReadBuffer->overlapped, nullptr);

    if (ret == SOCKET_ERROR) {
        int err = ::WSAGetLastError();
        if (err != WSA_IO_PENDING) {
            NetException e;
            e[NetException::Error] << "udp::prime_read failed: " << err;
            throw e;
        }
    }
}

void udp::connect(const std::string& addr, int port, bool nonblock)
{
    NetException exception;

    addrinfo hints{};
    hints.ai_family   = AF_UNSPEC;
    hints.ai_socktype = SOCK_DGRAM;
    hints.ai_protocol = IPPROTO_UDP;

    addrinfo* result = nullptr;

    char serv[32];
    std::snprintf(serv, sizeof(serv), "%d", port);

    int gai = ::getaddrinfo(addr.c_str(), serv, &hints, &result);
    if (gai != 0) {
        exception[NetException::Error]
            << "udp::connect: getaddrinfo failed: " << gai_strerrorA(gai);
        throw exception;
    }

    for (addrinfo* rp = result; rp; rp = rp->ai_next) {

        // -------------------------------------------------------
        // 1) ensure socket exists and matches family
        // -------------------------------------------------------
        if (_Socket != INVALID_SOCKET) {
            // if family mismatch, close and recreate
            sockaddr_storage tmp{};
            int tmpLen = sizeof(tmp);
            if (::getsockname(_Socket, (sockaddr*)&tmp, &tmpLen) == 0) {
                if (tmp.ss_family != rp->ai_family) {
                    ::closesocket(_Socket);
                    _Socket = INVALID_SOCKET;
                }
            }
        }

        if (_Socket == INVALID_SOCKET) {
            _Socket = ::socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
            if (_Socket == INVALID_SOCKET)
                continue;
        }

        // -------------------------------------------------------
        // 2) set nonblock BEFORE connect() if requested
        // -------------------------------------------------------
        if (nonblock) {
            try {
                setNonBlock();
            } catch (...) {
                ::closesocket(_Socket);
                _Socket = INVALID_SOCKET;
                continue;
            }
        }

        // -------------------------------------------------------
        // 3) connect()
        // -------------------------------------------------------
        if (::connect(_Socket, rp->ai_addr, (int)rp->ai_addrlen) == 0) {
            // connected immediately
            setAddrFromAI(rp);

            ::freeaddrinfo(result);
            return;
        }

        // -------------------------------------------------------
        // 4) nonblocking in progress
        // -------------------------------------------------------
        int err = ::WSAGetLastError();
        if (nonblock && (err == WSAEWOULDBLOCK || err == WSAEINPROGRESS)) {
            setAddrFromAI(rp);

            ::freeaddrinfo(result);

            NetException n;
            n[NetException::Note] << "udp::connect: WSAEWOULDBLOCK";
            throw n; // caller waits for completion
        }

        // -------------------------------------------------------
        // 5) fatal error -> try next addrinfo
        // -------------------------------------------------------
        ::closesocket(_Socket);
        _Socket = INVALID_SOCKET;
    }

    ::freeaddrinfo(result);

    exception[NetException::Error]
        << "udp::connect: could not connect to "
        << addr << ":" << port;
    throw exception;
}

void udp::getAddress(std::string& addr) {
    char buf[INET6_ADDRSTRLEN]{};

    sockaddr* sa = reinterpret_cast<sockaddr*>(&_Addr);

    if (sa->sa_family == AF_INET) {
        inet_ntop(AF_INET, &reinterpret_cast<sockaddr_in*>(sa)->sin_addr, buf, sizeof(buf));
        addr = buf;
    } else if (sa->sa_family == AF_INET6) {
        inet_ntop(AF_INET6, &reinterpret_cast<sockaddr_in6*>(sa)->sin6_addr, buf, sizeof(buf));
        addr = buf;
    } else {
        addr = "";
    }
}

} // namespace netplus
