/*Copyright (C) 2010-2023 Duncan Deveaux

This file is part of Hikou no mizu.

Hikou no mizu is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Hikou no mizu is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Hikou no mizu.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "Address.hpp"

#include <cstddef>
#include <stdexcept>

Address::Address() : Address(0, 0) {}
Address::Address(const ENetAddress &address) : m_enetAddr(address) {}

Address::Address(enet_uint32 host, enet_uint16 port)
{
    m_enetAddr.host = host;
    m_enetAddr.port = port;
}

Address::Address(const std::string &host, enet_uint16 port)
{
    setHost(host);
    m_enetAddr.port = port;
}

bool Address::setHost(const std::string &hostName)
{
    return (enet_address_set_host(&m_enetAddr, hostName.c_str()) == 0);
}

bool Address::setPort(const std::string &port)
{
    const std::uint16_t uintPort = readPort(port);
    if (uintPort == 0)
        return false;

    m_enetAddr.port = uintPort;
    return true;
}

std::string Address::getHostIP() const
{
    constexpr std::size_t length = 16;

    char ip[length];
    if (enet_address_get_host_ip(&m_enetAddr, ip, length) < 0)
        return "???";

    return std::string(ip);
}

std::uint16_t Address::getPort() const
{
    return m_enetAddr.port;
}

std::uint16_t Address::readPort(const std::string &port)
{
    if (port.length() > 5)
        return 0;

    try
    {
        const int intPort = std::stoi(port);
        if (intPort >= 1 && intPort <= 65535)
            return static_cast<std::uint16_t>(intPort);
    }
    catch (const std::exception &) {}

    return 0;
}
