/*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 "PeerPingMessage.hpp"

#include "Tools/ByteTools.hpp"
#include "Tools/Log.hpp"

////////////////////
///PingSerializer///
////////////////////
PingSerializer::PingSerializer() : PingSerializer(0) {}
PingSerializer::PingSerializer(std::uint32_t ping) : m_ping(ping) {}

bool PingSerializer::readFromBuffer(std::list<std::uint8_t> &bytes)
{
    return ByteTools::readUnsigned<std::uint32_t, 2>(bytes, m_ping);
}

bool PingSerializer::writeToBuffer(std::list<std::uint8_t> &dst) const
{
    ByteTools::writeUnsigned<std::uint32_t, 2>(m_ping, dst);
    return true;
}

std::uint32_t PingSerializer::getPing() const
{
    return m_ping;
}

/////////////////////
///PeerPingMessage///
/////////////////////
PeerPingMessage::PeerPingMessage(const std::vector<std::uint32_t> &pings) :
Message(), m_pings(pings.begin(), pings.end())
{

}

bool PeerPingMessage::fromBuffer(const Message::Buffer &buffer)
{
    std::list<std::uint8_t> bytes = buffer.bytes();
    return ByteTools::readList(bytes, m_pings);
}

Message::Buffer PeerPingMessage::allocBuffer() const
{
    std::list<std::uint8_t> bytes;
    if (!ByteTools::writeList(m_pings, bytes))
        return Message::Buffer();

    return Message::Buffer::alloc(bytes);
}

std::vector<std::uint32_t> PeerPingMessage::getPings() const
{
    std::vector<std::uint32_t> pings;
    pings.reserve(m_pings.size());

    for (const PingSerializer &serializer : m_pings)
        pings.push_back(serializer.getPing());

    return pings;
}
