/*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_SERVER_HOST
#define DEF_SERVER_HOST

#include "Channel.hpp"
#include "KickReason.hpp"
#include <enet/enet.h>
#include <map>
#include <cstdint>
#include <cstddef>

class Address;
class Message;

/// Abstract class to extend in order to catch server host-related callbacks
class ServerHostCallbackReceiver
{
    public:
        virtual ~ServerHostCallbackReceiver() {}
        virtual void peerConnectedCallback(std::uint16_t peerID) = 0;
        virtual void messageReceivedCallback(std::uint16_t peerID,
                                             const ENetPacket &packet,
                                             Channel channel) = 0;
        virtual void peerDisconnectedCallback(std::uint16_t peerID) = 0;
};

class ServerHost
{
    public:
        ServerHost();
        ServerHost(const ServerHost &copied) = delete;
        ServerHost &operator=(const ServerHost &copied) = delete;
        ~ServerHost();
        void destroy();

        bool init(const Address &address, std::size_t peerLimit);
        void setHostCallbackReceiver(ServerHostCallbackReceiver *receiver);

        void listen();

        void send(const Message &message, std::uint16_t peerID, Channel channel,
                  bool forceReliable = false /**< Send a reliable message,
                  overriding the channel default*/);
        void flush();

        void kick(std::uint16_t peerID, KickReason reason);

        std::uint32_t getPing(std::uint16_t peerID) const;
        Address getAddress(std::uint16_t peerID) const;

    private:
        void receive(std::uint16_t peerID, const ENetPacket &packet,
                     enet_uint8 channelID) const;

        ENetHost *m_enetServer;
        std::map<std::uint16_t, ENetPeer*> m_peers; ///< List of connected peers

        ServerHostCallbackReceiver *m_callbackReceiver;
};

#endif
