/*******************************************************************************
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 "error.h"

#include <cstdio>
#include <cstring>
#include <cerrno>
#include <iostream>
#include <unistd.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <sys/un.h>

namespace netplus {

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

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

udp::~udp() {
    if (_Socket >= 0)
        socket::close();
}

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

    if (sockopts == -1)
        sockopts = SO_REUSEADDR;

    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: " << gai_strerror(gai);
        throw e;
    }

    for (addrinfo* rp = result; rp; rp = rp->ai_next) {
        _Socket = ::socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
        if (_Socket < 0)
            continue;

        setAddrFromAI(rp);
        break;
    }

    ::freeaddrinfo(result);

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

    int opt = 1;
    if (sockopts & SO_REUSEADDR)
        ::setsockopt(_Socket, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
#ifdef SO_REUSEPORT
    if (sockopts & SO_REUSEPORT)
        ::setsockopt(_Socket, SOL_SOCKET, SO_REUSEPORT, &opt, sizeof(opt));
#endif

}

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

    if ((_Socket = ::socket(AF_UNIX, SOCK_DGRAM, 0)) < 0) {
        NetException e;
        e[NetException::Critical] << "Can't create Unix UDP Socket";
        throw e;
    }

    sockaddr_un un{};
    un.sun_family = AF_UNIX;
    std::snprintf(un.sun_path, sizeof(un.sun_path), "%s", uxsocket.c_str());

    std::memset(&_Addr, 0, sizeof(_Addr));
    std::memcpy(&_Addr, &un, sizeof(un));
    _AddrLen = sizeof(un);

    int opt = 1;
    if (sockopts == -1) sockopts = SO_REUSEADDR;

    if (sockopts & SO_REUSEADDR)
        ::setsockopt(_Socket, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
#ifdef SO_REUSEPORT
    if (sockopts & SO_REUSEPORT)
        ::setsockopt(_Socket, SOL_SOCKET, SO_REUSEPORT, &opt, sizeof(opt));
#endif
}

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

void udp::listen() {
    // UDP has no listen
    _Listening = true;
}

void udp::setNonBlock() {
    setFlag(O_NONBLOCK, 1);
}

void udp::setBlock() {
    setFlag(O_NONBLOCK, 0);
}

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

udp& udp::operator=(SOCKET s) {
    _Socket = s;
    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) {
    const char* p = data.ptr ? data.data.ptr : data.data.buf;
    ssize_t s = ::send(_Socket, p, data.size, flags);

    if (s < 0) {
        if (errno == EAGAIN || errno == EWOULDBLOCK) {
            NetException e;
            e[NetException::Note] << "udp::sendData would block";
            throw e;
        }
        NetException e;
        e[NetException::Error] << "udp::sendData failed: " << strerror(errno);
        throw e;
    }

    return (size_t)s;
}

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

    if (s < 0) {
        if (errno == EAGAIN || errno == EWOULDBLOCK) {
            NetException e;
            e[NetException::Note] << "udp::sendTo would block";
            throw e;
        }
        NetException e;
        e[NetException::Error] << "udp::sendTo failed: " << strerror(errno);
        throw e;
    }

    return (size_t)s;
}

size_t udp::recvData(buffer& data, int flags) {
    sockaddr_storage peer{};
    socklen_t peerLen = sizeof(peer);

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

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

    if (errno == EAGAIN || errno == EWOULDBLOCK) {
        NetException e;
        e[NetException::Note] << "udp::recvData would block";
        throw e;
    }

    NetException e;
    e[NetException::Error] << "udp::recvData failed: " << strerror(errno);
    throw e;
}

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

    addrinfo hints{};
    hints.ai_family   = AF_UNSPEC;      // IPv4 oder IPv6
    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_strerror(gai);
        throw exception;
    }

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

        // ✅ Socket erstellen falls nicht da
        if (_Socket < 0) {
            _Socket = ::socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
            if (_Socket < 0)
                continue;
        }

        // ✅ connect UDP (bindet Default Peer)
        if (::connect(_Socket, rp->ai_addr, rp->ai_addrlen) == 0) {

            // ✅ Adresse sauber speichern (deep copy)
            copyAddrInfo(&_SocketInfo,
                         reinterpret_cast<ULONG_PTR>(rp),
                         sizeof(addrinfo));

            _SocketInfoLen = rp->ai_addrlen;

            ::freeaddrinfo(result);
            return;
        }

        // Fehler -> neuen Socket versuchen
        ::close(_Socket);
        _Socket = -1;
    }

    ::freeaddrinfo(result);

    exception[NetException::Error]
        << "udp::connect: could not connect to " << addr << ":" << port
        << " (" << strerror(errno) << ")";
    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 = "";
    }
}

void udp::flush_out() {
}

} // namespace netplus
