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

#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <WinSock2.h>
#include <mswsock.h>
#include <ws2tcpip.h>

#pragma comment(lib, "Ws2_32.lib")

#include <atomic>
#include <thread>
#include <chrono>
#include <vector>
#include <memory>
#include <mutex>
#include <unordered_map>
#include <iostream>
#include <algorithm>
#include <cstring>

#include "socket.h"
#include "exception.h"
#include "eventapi.h"
#include "connection.h"

#ifndef BLOCKSIZE
#define BLOCKSIZE 16384
#endif

namespace netplus {

    // -------------------------------------------------------------------------
    // Per-event state
    // -------------------------------------------------------------------------
    struct EventState {
        HANDLE iocp = nullptr;

        std::mutex conMutex;
        std::unordered_map<SOCKET, std::shared_ptr<con>> sockToCon;

        std::vector<std::thread> workers;
        std::vector<std::thread> acceptThreads;
        int threads = 1;
    };

    static std::mutex g_stateMutex;
    static std::unordered_map<event*, std::unique_ptr<EventState>> g_states;

    static EventState* ST(event* ev) {
        std::lock_guard<std::mutex> lk(g_stateMutex);
        auto it = g_states.find(ev);
        if (it == g_states.end()) return nullptr;
        return it->second.get();
    }

    // -------------------------------------------------------------------------
    // Connection helpers
    // -------------------------------------------------------------------------
    static void register_con(EventState* st, SOCKET s, std::shared_ptr<con> c) {
        std::lock_guard<std::mutex> lk(st->conMutex);
        st->sockToCon[s] = c;
    }

    static std::shared_ptr<con> find_con(EventState* st, SOCKET s) {
        std::lock_guard<std::mutex> lk(st->conMutex);
        auto it = st->sockToCon.find(s);
        if (it == st->sockToCon.end()) return nullptr;
        return it->second;
    }

    static void remove_con(EventState* st, SOCKET s) {
        std::lock_guard<std::mutex> lk(st->conMutex);
        st->sockToCon.erase(s);
    }

    static bool mark_closing(con* c) {
        bool expected = false;
        return c->slots[0].Closing.compare_exchange_strong(expected, true);
    }

    static bool try_cleanup_con(event* ev, EventState* st, con* owner, SOCKET cs, int tid) {
        if (!mark_closing(owner)) return false;
        if (owner->slots[0].WritePending.load()) return false;
        ev->DisconnectEvent(*owner, tid, 0);
        remove_con(st, cs);
        try { owner->slots[0].csock->close(); } catch (...) {}
        return true;
    }

    // -------------------------------------------------------------------------
    // Ensure persistent recv buffer exists for a connection
    // -------------------------------------------------------------------------
    static buffer* ensure_recv_buffer(EventState* /*st*/, con& c) {
        if (!c.slots[0].csock->_ReadBuffer) {
            c.slots[0].csock->_ReadBuffer = std::make_unique<buffer>(BLOCKSIZE);
        }
        buffer* b = c.slots[0].csock->_ReadBuffer.get();
        b->operation = OP_READ;
        b->owner = &c;
        return b;
    }

    // -------------------------------------------------------------------------
    // Post receive for a connection (only if not already pending)
    // -------------------------------------------------------------------------
    static void post_recv(EventState* st, con& c) {
        if (c.slots[0].Closing.load()) return;

        bool expected = false;
        if (!c.slots[0].ReadPending.compare_exchange_strong(expected, true)) return;

        buffer* b = ensure_recv_buffer(st, c);
        std::memset(&b->overlapped, 0, sizeof(WSAOVERLAPPED));
        b->operation = OP_READ;
        b->owner = &c;

        c.slots[0].csock->prime_read();
    }

    // -------------------------------------------------------------------------
    // Post send (only if not already pending)
    // -------------------------------------------------------------------------
    static bool try_post_send(event* ev, EventState* /*st*/, con& c, int tid) {
        if (c.slots[0].Closing.load()) return false;
        if (c.slots[0].WritePending.load()) return false;
        if (c.SendData.empty()) return false;

        c.slots[0].WritePending.store(true);

        try {
            size_t sendlen = std::min<size_t>(c.SendData.size(), BLOCKSIZE);
            const char* ptr = c.SendData.data();

            buffer sbuf(ptr, sendlen);
            size_t consumed = c.slots[0].csock->sendData(sbuf, 0);

            if (consumed > 0) {
                c.SendData.erase(c.SendData.begin(), c.SendData.begin() + consumed);
            }

            if (c.slots[0].csock->hasPendingWrite()) {
                return true;
            }

            c.slots[0].WritePending.store(false);

            if (!c.SendData.empty()) {
                return try_post_send(ev, nullptr, c, tid);
            }

            return false;
        } catch (NetException& e) {
            c.slots[0].WritePending.store(false);
            if (e.getErrorType() != NetException::Note) throw;
            return false;
        }
    }

    // -------------------------------------------------------------------------
    // init EventState for an event instance
    // -------------------------------------------------------------------------
    static void init_state(event* ev) {
        std::lock_guard<std::mutex> lk(g_stateMutex);
        if (g_states.find(ev) != g_states.end()) return;

        auto st = std::make_unique<EventState>();

        st->iocp = CreateIoCompletionPort(INVALID_HANDLE_VALUE, nullptr, 0, 0);
        if (!st->iocp) {
            NetException e;
            e[NetException::Critical] << "CreateIoCompletionPort failed: " << GetLastError();
            throw e;
        }

        st->threads = ev->threads;
        g_states[ev] = std::move(st);
    }

    // -------------------------------------------------------------------------
    // Accept loop - runs in dedicated thread per server socket
    // -------------------------------------------------------------------------
    static void accept_loop(event* ev, socket* serverSock) {
        EventState* st = ST(ev);

        while (event::Running) {
            // Use select() with timeout before blocking accept() so we can
            // periodically check event::Running and exit cleanly when the
            // service is stopped.  Calling closesocket() from another thread
            // to interrupt a blocking accept() is undefined behavior on Windows.
            {
                SOCKET sfd = (SOCKET)serverSock->fd();
                fd_set rset;
                FD_ZERO(&rset);
                FD_SET(sfd, &rset);
                timeval tv;
                tv.tv_sec = 1;
                tv.tv_usec = 0;
                int r = ::select(0, &rset, nullptr, nullptr, &tv);
                if (r == 0) continue;           // timeout — re-check Running
                if (r == SOCKET_ERROR) {
                    if (!event::Running) break;
                    std::this_thread::sleep_for(std::chrono::milliseconds(10));
                    continue;
                }
            }
            if (!event::Running) break;

            std::unique_ptr<socket> csock;

            // Pre-allocate the child socket based on server socket type
            // (ssl::accept handles its own allocation internally)
            if (serverSock->_Type == sockettype::TCP) {
                csock = std::make_unique<tcp>(INVALID_SOCKET);
            }

            try {
                serverSock->accept(csock, false);
            } catch (NetException& e) {
                if (!event::Running) break;
                if (e.getErrorType() == NetException::Note) {
                    std::this_thread::sleep_for(std::chrono::milliseconds(1));
                    continue;
                }
                std::cerr << "accept failed: " << e.what() << std::endl;
                std::this_thread::sleep_for(std::chrono::milliseconds(10));
                continue;
            } catch (...) {
                if (!event::Running) break;
                std::this_thread::sleep_for(std::chrono::milliseconds(10));
                continue;
            }

            if (!csock) {
                std::this_thread::sleep_for(std::chrono::milliseconds(1));
                continue;
            }

            SOCKET accepted = csock->fd();
            if (accepted == INVALID_SOCKET) continue;

            std::shared_ptr<con> c;
            ev->CreateConnection(c);

            if (!c) {
                csock->close();
                continue;
            }

            c->slots[0].csock = std::move(csock);

            HANDLE h = CreateIoCompletionPort((HANDLE)accepted,
                                              st->iocp,
                                              (ULONG_PTR)c->slots[0].csock.get(),
                                              0);
            if (!h) {
                c->slots[0].csock->close();
                continue;
            }

            c->slots[0].csock->setIocpAssociated(true);

            register_con(st, accepted, c);

            ev->ConnectEvent(*c, 0, 0);

            try {
                post_recv(st, *c);
            } catch (...) {
                ev->DisconnectEvent(*c, 0, 0);
                remove_con(st, accepted);
                try { c->slots[0].csock->close(); } catch (...) {}
            }
        }
    }

    // -------------------------------------------------------------------------
    // Worker loop
    // -------------------------------------------------------------------------
    class EventWorker {
    public:
        void operator()(event* ev, int tid) {
            EventState* st = ST(ev);

            try {
                while (event::Running) {
                    DWORD bytes = 0;
                    ULONG_PTR key = 0;
                    OVERLAPPED* pov = nullptr;

                    BOOL ok = GetQueuedCompletionStatus(st->iocp, &bytes, &key, &pov, 1000);
                    if (!event::Running) break;
                    if (!ok && !pov) continue;   // timeout or spurious wake
                    if (!pov && key == 0) continue;

                    socket* sockObj = reinterpret_cast<socket*>(key);
                    if (!sockObj) continue;

                    buffer* buf = nullptr;
                    if (pov) {
                        buf = reinterpret_cast<buffer*>(
                            reinterpret_cast<char*>(pov) - offsetof(buffer, overlapped)
                        );
                    }
                    if (!buf) continue;

                    SOCKET cs = (SOCKET)sockObj->fd();
                    std::shared_ptr<con> conPtr = find_con(st, cs);
                    if (!conPtr) continue;
                    con* owner = conPtr.get();

                    // ===== READ completion =====
                    if (buf->operation == OP_READ) {
                        std::lock_guard<std::recursive_mutex> lock(owner->event_mutex);

                        // Push received data into socket buffer
                        if (bytes > 0) {
                            owner->slots[0].csock->pushReceivedData(
                                reinterpret_cast<const uint8_t*>(buf->data.buf),
                                bytes
                            );
                        }

                        if (!ok) {
                            owner->slots[0].ReadPending.store(false);
                            if (mark_closing(owner)) {
                                if (!owner->slots[0].WritePending.load()) {
                                    ev->DisconnectEvent(*owner, tid, 0);
                                    remove_con(st, cs);
                                    try { owner->slots[0].csock->close(); } catch (...) {}
                                }
                            }
                            continue;
                        }

                        if (bytes == 0) {
                            owner->slots[0].ReadPending.store(false);
                            owner->slots[0].PeerClosed.store(true);
                            if (!mark_closing(owner)) continue;
                            if (owner->slots[0].WritePending.load()) continue;

                            try { owner->slots[0].csock->close(); } catch (...) {}
                            if (owner->slots[0].WritePending.load() || owner->slots[0].csock->hasPendingWrite()) continue;

                            ev->DisconnectEvent(*owner, tid, 0);
                            remove_con(st, cs);
                            continue;
                        }

                        // Handshake processing
                        bool continueHandshake = true;
                        while (continueHandshake && !owner->slots[0].csock->getHandshakeDone()) {
                            continueHandshake = false;

                            try {
                                owner->slots[0].csock->handshake_after_accept();
                            } catch (NetException& e) {
                                if (e.getErrorType() == NetException::Note) {
                                    if (owner->slots[0].csock->hasPendingWrite()) {
                                        try { owner->slots[0].csock->flush_out(); } catch (...) {}
                                    }
                                    owner->slots[0].ReadPending.store(false);
                                    try { post_recv(st, *owner); } catch (...) {}
                                    continueHandshake = false;
                                } else {
                                    owner->slots[0].ReadPending.store(false);
                                    try_cleanup_con(ev, st, owner, cs, tid);
                                    continueHandshake = false;
                                }
                            } catch (...) {
                                owner->slots[0].ReadPending.store(false);
                                try_cleanup_con(ev, st, owner, cs, tid);
                                continueHandshake = false;
                            }

                            if (!owner->slots[0].csock->getHandshakeDone()) {
                                if (owner->slots[0].csock->hasBufferedData()) {
                                    continueHandshake = true;
                                } else {
                                    owner->slots[0].ReadPending.store(false);
                                    try { post_recv(st, *owner); } catch (...) {}
                                }
                            }
                        }

                        if (!owner->slots[0].csock->getHandshakeDone()) continue;

                        // Post-handshake framing callback (e.g. HTTP/2 SETTINGS)
                        if (auto *sslsock = dynamic_cast<ssl*>(owner->slots[0].csock.get())) {
                            const auto &fcb = sslsock->getFramingCallback();
                            if (fcb && owner->SendData.empty()) {
                                std::string init = fcb(sslsock->getSelectedAlpn(), 0, "", "");
                                if (!init.empty()) {
                                    owner->SendData.append(init.data(), init.size());
                                }
                            }
                        }

                        // Application data: drain all available records
                        try {
                            while (true) {
                                buffer decrypted(BLOCKSIZE);
                                size_t decLen = 0;
                                bool wouldBlock = false;

                                try {
                                    decLen = owner->slots[0].csock->recvData(decrypted, 0);
                                } catch (NetException& e) {
                                    if (e.getErrorType() == NetException::Note) {
                                        wouldBlock = true;
                                    } else {
                                        throw;
                                    }
                                }

                                if (wouldBlock || decLen == 0) break;

                                owner->RecvData.append(decrypted.data.buf, decLen);
                                ev->RequestEvent(*owner, tid, (ULONG_PTR)decLen);

                                if (!owner->slots[0].csock->hasBufferedData()) break;
                            }
                        } catch (NetException& e) {
                            if (e.getErrorType() != NetException::Note) {
                                owner->slots[0].ReadPending.store(false);
                                try_cleanup_con(ev, st, owner, cs, tid);
                                continue;
                            }
                        }

                        // Send queued data
                        try {
                            try_post_send(ev, st, *owner, tid);
                        } catch (...) {
                            owner->slots[0].ReadPending.store(false);
                            try_cleanup_con(ev, st, owner, cs, tid);
                            continue;
                        }

                        // Repost recv
                        owner->slots[0].ReadPending.store(false);
                        try {
                            post_recv(st, *owner);
                        } catch (...) {
                            try_cleanup_con(ev, st, owner, cs, tid);
                            continue;
                        }
                    }
                    // ===== WRITE completion =====
                    else if (buf->operation == OP_WRITE) {
                        if (bytes == 0 && !ok) {
                            owner->slots[0].WritePending.store(false);
                            try_cleanup_con(ev, st, owner, cs, tid);
                            continue;
                        }

                        if (owner->slots[0].Closing.load()) {
                            owner->slots[0].WritePending.store(false);
                            ev->DisconnectEvent(*owner, tid, 0);
                            remove_con(st, cs);
                            try { owner->slots[0].csock->close(); } catch (...) {}
                            continue;
                        }

                        // Write completed during handshake
                        if (!owner->slots[0].csock->getHandshakeDone()) {
                            owner->slots[0].WritePending.store(false);
                            owner->slots[0].csock->setPendingWrite(false);

                            std::lock_guard<std::recursive_mutex> hsLock(owner->event_mutex);
                            try {
                                owner->slots[0].csock->handshake_after_accept();

                                try { post_recv(st, *owner); } catch (...) {}
                            } catch (NetException& e) {
                                if (e.getErrorType() == NetException::Note) {
                                    try { post_recv(st, *owner); } catch (...) {}
                                } else {
                                    try_cleanup_con(ev, st, owner, cs, tid);
                                }
                            } catch (...) {
                                try_cleanup_con(ev, st, owner, cs, tid);
                            }
                            continue;
                        }

                        // Application write completion
                        {
                            std::lock_guard<std::recursive_mutex> lock(owner->event_mutex);

                            owner->slots[0].WritePending.store(false);
                            owner->slots[0].csock->setPendingWrite(false);

                            if (owner->slots[0].Closing.load()) {
                                ev->DisconnectEvent(*owner, tid, 0);
                                remove_con(st, cs);
                                try { owner->slots[0].csock->close(); } catch (...) {}
                                continue;
                            }

                            try {
                                if (owner->SendData.empty() && !owner->slots[0].csock->hasPendingWrite()) {
                                    ev->ResponseEvent(*owner, tid, (ULONG_PTR)bytes);
                                }

                                if (!owner->SendData.empty()) {
                                    bool posted = try_post_send(ev, st, *owner, tid);
                                    if (posted) continue;
                                }

                                // App requested re-trigger (e.g. upstream data not yet available)
                                if (owner->SendData.empty() && owner->slots[0].ResponsePending.exchange(false, std::memory_order_relaxed)) {
                                    ev->ResponseEvent(*owner, tid, 0);
                                    if (!owner->SendData.empty()) {
                                        bool posted = try_post_send(ev, st, *owner, tid);
                                        if (posted) continue;
                                    }
                                }

                                if (owner->SendData.empty() && !owner->slots[0].csock->hasPendingWrite() && !owner->slots[0].Closing.load()) {
                                    try { post_recv(st, *owner); } catch (...) {}
                                }
                            } catch (...) {
                                try_cleanup_con(ev, st, owner, cs, tid);
                            }
                        }
                    }
                }

            } catch (std::exception& e) {
                std::cerr << "EventWorker thread exception: " << e.what() << std::endl;
            } catch (...) {
                std::cerr << "EventWorker thread unknown exception" << std::endl;
            }
        }
    };

    // -------------------------------------------------------------------------
    // eventapi dummies (not needed on IOCP path since virtuals must be overridden)
    // but provided for linkage
    // -------------------------------------------------------------------------

    // -------------------------------------------------------------------------
    // event implementation
    // -------------------------------------------------------------------------
    event::event(std::vector<socket*> serversockets, int timeout)
        : _ServerSockets(serversockets), _Timeout(timeout)
    {
        if (_ServerSockets.empty()) {
            NetException e;
            e[NetException::Critical] << "server socket empty!";
            throw e;
        }

        WSADATA wsaData;
        int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
        if (iResult != 0) {
            NetException e;
            e[NetException::Critical] << "WSAStartup failed: " << iResult;
            throw e;
        }

        for (auto* s : _ServerSockets) {
            if (!s) continue;
            s->bind();
            s->listen();
            s->setTimeout(timeout);
        }

        threads = (int)std::max<unsigned>(1, std::thread::hardware_concurrency());
    }

    event::event(const event& src) : _ServerSockets(src._ServerSockets), _Timeout(src._Timeout) {}

    event::~event() {
        Running = false;

        EventState* st = ST(this);
        if (!st) {
            WSACleanup();
            return;
        }

        // Close server sockets to unblock accept threads
        for (auto* s : _ServerSockets) {
            if (s) {
                try { closesocket((SOCKET)s->fd()); } catch (...) {}
            }
        }

        // Cancel all pending I/O on registered connections
        {
            std::lock_guard<std::mutex> lk(st->conMutex);
            for (auto& kv : st->sockToCon) {
                CancelIoEx((HANDLE)kv.first, nullptr);
            }
        }

        // Wake all workers
        for (int round = 0; round < 3; ++round) {
            for (size_t i = 0; i < st->workers.size(); ++i) {
                PostQueuedCompletionStatus(st->iocp, 0, 0, nullptr);
            }
        }

        for (auto& t : st->acceptThreads) {
            if (t.joinable()) t.join();
        }
        st->acceptThreads.clear();

        for (auto& t : st->workers) {
            if (t.joinable()) t.join();
        }
        st->workers.clear();

        if (st->iocp) {
            CloseHandle(st->iocp);
            st->iocp = nullptr;
        }

        {
            std::lock_guard<std::mutex> lk(g_stateMutex);
            g_states.erase(this);
        }

        WSACleanup();
    }

    void event::runEventloop(ULONG_PTR /*args*/) {
        init_state(this);

        EventState* st = ST(this);
        _pollFD = (int)(intptr_t)st->iocp;

        Running = true;

        // Start dedicated accept thread per server socket
        for (auto* ss : _ServerSockets) {
            if (!ss) continue;
            st->acceptThreads.emplace_back([=]() {
                accept_loop(this, ss);
            });
        }

        // Start worker threads
        for (int i = 0; i < st->threads; ++i) {
            st->workers.emplace_back([=]() {
                EventWorker()(this, i);
            });
        }

        // Block like epoll loop (join workers, then accept threads)
        for (auto& t : st->workers) {
            if (t.joinable()) t.join();
        }
        st->workers.clear();

        for (auto& t : st->acceptThreads) {
            if (t.joinable()) t.join();
        }
        st->acceptThreads.clear();
    }

    // ================================================================
    // socketwait – Windows implementation using select()
    // ================================================================
    socketwait::socketwait() : _handle(-1) {}
    socketwait::~socketwait() {}

    bool socketwait::waitRead(socket &sock, int timeout_ms) {
        SOCKET fd = sock.fd();
        if (fd == INVALID_SOCKET) return false;
        fd_set rset, eset;
        FD_ZERO(&rset); FD_SET(fd, &rset);
        FD_ZERO(&eset); FD_SET(fd, &eset);
        timeval tv_buf;
        timeval* tvp = nullptr;
        if (timeout_ms >= 0) {
            tv_buf.tv_sec  = timeout_ms / 1000;
            tv_buf.tv_usec = (timeout_ms % 1000) * 1000;
            tvp = &tv_buf;
        }
        int r = ::select(0, &rset, nullptr, &eset, tvp);
        if (r == SOCKET_ERROR) {
            NetException e;
            e[NetException::Error] << "socketwait::waitRead select() failed: " << WSAGetLastError();
            throw e;
        }
        return r > 0;
    }

    bool socketwait::waitWrite(socket &sock, int timeout_ms) {
        SOCKET fd = sock.fd();
        if (fd == INVALID_SOCKET) return false;
        fd_set wset, eset;
        FD_ZERO(&wset); FD_SET(fd, &wset);
        FD_ZERO(&eset); FD_SET(fd, &eset);
        timeval tv_buf;
        timeval* tvp = nullptr;
        if (timeout_ms >= 0) {
            tv_buf.tv_sec  = timeout_ms / 1000;
            tv_buf.tv_usec = (timeout_ms % 1000) * 1000;
            tvp = &tv_buf;
        }
        int r = ::select(0, nullptr, &wset, &eset, tvp);
        if (r == SOCKET_ERROR) {
            NetException e;
            e[NetException::Error] << "socketwait::waitWrite select() failed: " << WSAGetLastError();
            throw e;
        }
        return r > 0 && FD_ISSET(fd, &wset);
    }

    int socketwait::waitReadMulti(std::vector<socket*> &sockets,
                                   std::vector<bool> &ready,
                                   int timeout_ms) {
        size_t n = sockets.size();
        ready.assign(n, false);
        if (n == 0) return 0;

        fd_set rset, eset;
        FD_ZERO(&rset); FD_ZERO(&eset);
        for (size_t i = 0; i < n; ++i) {
            if (!sockets[i]) continue;
            SOCKET fd = sockets[i]->fd();
            if (fd == INVALID_SOCKET) continue;
            FD_SET(fd, &rset);
            FD_SET(fd, &eset);
        }
        timeval tv_buf;
        timeval* tvp = nullptr;
        if (timeout_ms >= 0) {
            tv_buf.tv_sec  = timeout_ms / 1000;
            tv_buf.tv_usec = (timeout_ms % 1000) * 1000;
            tvp = &tv_buf;
        }
        int r = ::select(0, &rset, nullptr, &eset, tvp);
        if (r <= 0) return 0;
        int count = 0;
        for (size_t i = 0; i < n; ++i) {
            if (!sockets[i]) continue;
            SOCKET fd = sockets[i]->fd();
            if (fd == INVALID_SOCKET) continue;
            if (FD_ISSET(fd, &rset) || FD_ISSET(fd, &eset)) {
                ready[i] = true;
                ++count;
            }
        }
        return count;
    }

    bool socketwait::isDisconnected(socket &sock) {
        SOCKET fd = sock.fd();
        if (fd == INVALID_SOCKET) return true;
        fd_set rset, eset;
        FD_ZERO(&rset); FD_SET(fd, &rset);
        FD_ZERO(&eset); FD_SET(fd, &eset);
        timeval tv{0, 0};
        int r = ::select(0, &rset, nullptr, &eset, &tv);
        if (r == SOCKET_ERROR) return true;
        if (r == 0) return false;
        if (FD_ISSET(fd, &eset)) return true;
        if (FD_ISSET(fd, &rset)) {
            char tmp;
            int n = ::recv(fd, &tmp, 1, MSG_PEEK);
            if (n == 0 || n == SOCKET_ERROR) return true;
        }
        return false;
    }

} // namespace netplus
