/*******************************************************************************
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 {

tcp::tcp() : socket() {
    _Socket = INVALID_SOCKET;
    _Type = sockettype::TCP;
}

tcp::tcp(SOCKET sock) : socket() {
    _Socket = sock;
    _Type = sockettype::TCP;
}

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

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

    addrinfo hints{};
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    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] << "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 TCP socket";
        throw e;
    }

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

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

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

void tcp::listen() {
    if (::listen(_Socket, _Maxconnections) == SOCKET_ERROR) {
        NetException e;
        e[NetException::Error] << "tcp::listen failed";
        throw e;
    }
}

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

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

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

void tcp::accept(std::unique_ptr<socket>& csock, bool nonblock) {
    if (!csock) {
        csock = std::make_unique<tcp>(INVALID_SOCKET);
    }

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

    SOCKET cfd = ::accept(_Socket, reinterpret_cast<sockaddr*>(&peer), &peerLen);
    if (cfd == INVALID_SOCKET) {
        int err = ::WSAGetLastError();
        NetException e;
        int et = (err == WSAEWOULDBLOCK) ? NetException::Note : NetException::Error;
        e[et] << "tcp::accept failed: " << err;
        throw e;
    }

    *csock = cfd;
    csock->_Addr = peer;
    csock->_AddrLen = peerLen;

    if (nonblock)
        csock->setNonBlock();
}

size_t tcp::sendData(buffer& data, int flags) {
    // Copy data to _SendBuffer for async WSASend
    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) {
            // Async operation started - completion will come via IOCP
            return sendlen;
        }
        _pendingIocpWrite.store(false);
        NetException e;
        e[NetException::Error] << "tcp::sendData WSASend failed: " << err;
        throw e;
    }
    
    // Completed synchronously - IOCP still gets completion notification
    return sendlen;
}

size_t tcp::recvData(buffer& data, int flags) {
    // First check if we have data from a completed IOCP read
    std::cerr << "[TCP] recvData: _ReadBuffer=" << (_ReadBuffer ? "yes" : "no");
    if (_ReadBuffer) {
        std::cerr << " InternalHigh=" << _ReadBuffer->overlapped.InternalHigh;
    }
    std::cerr << std::endl;
    
    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);
        std::cerr << "[TCP] recvData: returning " << r << " bytes from InternalHigh, resetting to 0" << std::endl;
        _ReadBuffer->overlapped.InternalHigh = 0;
        return r;
    }

    // Use WSARecv for blocking receive on client sockets
    WSABUF wsaBuf;
    wsaBuf.buf = data.data.buf;
    wsaBuf.len = (ULONG)data.size;
    
    DWORD bytesRecv = 0;
    DWORD dwFlags = (DWORD)flags;
    
    int ret = ::WSARecv(_Socket, &wsaBuf, 1, &bytesRecv, &dwFlags, nullptr, nullptr);
    
    if (ret == 0) {
        // Success
        if (bytesRecv > 0) {
            std::cerr << "[TCP] recvData: WSARecv returned " << bytesRecv << " bytes" << std::endl;
            return (size_t)bytesRecv;
        }
        // bytesRecv == 0 means connection closed
        std::cerr << "[TCP] recvData: connection closed" << std::endl;
        NetException e;
        e[NetException::Error] << "tcp::recvData: connection closed";
        throw e;
    }
    
    int err = ::WSAGetLastError();
    if (err == WSAEWOULDBLOCK) {
        // Non-blocking socket with no data - throw Note
        std::cerr << "[TCP] recvData: WSAEWOULDBLOCK, throwing Note" << std::endl;
        NetException e;
        e[NetException::Note] << "tcp::recvData: no data available";
        throw e;
    }
    
    std::cerr << "[TCP] recvData: WSARecv error " << err << std::endl;
    NetException e;
    e[NetException::Error] << "tcp::recvData: WSARecv failed with error " << err;
    throw e;
}

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

    addrinfo hints{};
    hints.ai_family   = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;

    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]
            << "tcp::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 = ::WSASocketA(rp->ai_family, rp->ai_socktype, rp->ai_protocol, nullptr, 0, WSA_FLAG_OVERLAPPED);
            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() - use WSAConnect for IOCP socket compatibility
        // -------------------------------------------------------
        if (::WSAConnect(_Socket, rp->ai_addr, (int)rp->ai_addrlen, nullptr, nullptr, nullptr, nullptr) == 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] << "tcp::connect: WSAEWOULDBLOCK";
            throw n; // caller waits for completion
        }

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

    ::freeaddrinfo(result);

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

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

void tcp::accept(LPFN_ACCEPTEX lpfnAcceptEx, std::unique_ptr<socket>& csock) {
    if (!csock) {
        csock = std::make_unique<tcp>();
    }
    // Create accept socket
    SOCKET acceptSock = ::WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, nullptr, 0, WSA_FLAG_OVERLAPPED);
    if (acceptSock == INVALID_SOCKET) {
        NetException e;
        e[NetException::Error] << "tcp::accept WSASocket failed";
        throw e;
    }

    // IOCP sockets should be non-blocking to prevent accidental blocking in recv/send
    u_long mode = 1;
    ::ioctlsocket(acceptSock, FIONBIO, &mode);

    if (!csock->_ReadBuffer)
        csock->_ReadBuffer.reset(new buffer);

    buffer* buf = csock->_ReadBuffer.get();

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

    DWORD bytesReceived = 0;
    BOOL result = lpfnAcceptEx(
        _Socket,
        acceptSock,
        buf->data.buf,
        0,
        sizeof(SOCKADDR_STORAGE) + 16,
        sizeof(SOCKADDR_STORAGE) + 16,
        &bytesReceived,
        &buf->overlapped
    );

    if (!result) {
        int err = ::WSAGetLastError();
        if (err != WSA_IO_PENDING) {
            ::closesocket(acceptSock);
            NetException e;
            e[NetException::Error] << "tcp::accept AcceptEx failed: " << err;
            throw e;
        }
    }

    // Store the accept socket for later retrieval
    // Note: *csock was already a valid object (managed by caller), but its _Socket needed to be set?
    // Wait, the caller passes csock which contains a new tcp object but _Socket is probably INVALID.
    // The acceptSock we created is the handle.
    // The previous implementation did: *csock = acceptSock;
    // But csock is unique_ptr<socket>. operator=(SOCKET) is virtual.
    *csock = acceptSock;
}

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

void tcp::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] << "tcp::prime_read failed: " << err;
            throw e;
        }
    }
}

void tcp::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
