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

#ifndef DEF_MESSAGE
#define DEF_MESSAGE

#include <cstddef>
#include <cstdint>
#include <algorithm>
#include <list>

/// A message to be transmitted and received between client and server hosts
class Message
{
    public:
        /// Represents a byte buffer, i.e., a pointer to uint8_t and a size
        struct Buffer
        {
            Buffer() : Buffer(nullptr, 0) {}

            Buffer(const std::uint8_t *bufferData, std::size_t bufferLength) :
            data(bufferData), length(bufferLength) {}

            static Buffer alloc(const std::list<std::uint8_t> &bytes)
            {
                std::uint8_t *buffer = nullptr;
                std::size_t length = bytes.size();

                if (!bytes.empty())
                {
                    buffer = new std::uint8_t[length];
                    std::copy(bytes.begin(), bytes.end(), buffer);
                }

                return Message::Buffer(buffer, length);
            }

            std::list<std::uint8_t> bytes() const
            {
                std::list<std::uint8_t> bytes;
                if (data != nullptr)
                    bytes.assign(data, data+length);

                return bytes;
            }

            void destroy()
            {
                if (data != nullptr)
                {
                    delete[] data;
                    data = nullptr;
                    length = 0;
                }
            }

            const std::uint8_t *data;
            std::size_t length;
        };

        virtual ~Message() = default;
        virtual bool fromBuffer(const Buffer &buffer) = 0;
        virtual Buffer allocBuffer() const = 0;
};

#endif
