/*
PolyGun

Copyright (c) 2023 mrkubax10 <mrkubax10@onet.pl>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

#ifndef POLYGUN_NETWORK_NETWORK_MANAGER_HPP
#define POLYGUN_NETWORK_NETWORK_MANAGER_HPP

#include <memory>

#include "common/network/network_packet.hpp"
#include "common/network/udp_socket.hpp"

namespace polygun::network {
	class NetworkManager final {
	public:
		struct QueuedPacket {
			NetworkPacket m_packet;
			time_t m_last_retry;
			uint8_t m_retries;
		};
	public:
		NetworkManager(std::shared_ptr<UDPSocket> socket, const NetworkEndpoint& endpoint);
		NetworkManager(const std::string& ip, unsigned short port);
		~NetworkManager() = default;

		NetworkPacket create_packet(uint8_t flags, uint8_t id);

		void send_packet(const NetworkPacket& packet);
		bool recv_packet(NetworkPacket& packet);
		void push_packet(NetworkPacket& packet);
		void send_ack(uint32_t packet_num) const;

		void update();

		void increment_incoming_packet_counter() { m_incoming_packet_counter++; }
		const NetworkEndpoint& get_endpoint() const { return m_endpoint; }
		UDPSocket& get_socket() { return *m_socket; }
		bool has_outgoing_packets() const { return m_outgoing_packets.size()>0; }

	private:
		uint32_t m_outgoing_packet_counter;
		uint32_t m_incoming_packet_counter;
		std::vector<QueuedPacket> m_outgoing_packets;
		std::vector<QueuedPacket> m_incoming_packets;
		std::shared_ptr<UDPSocket> m_socket;
		NetworkEndpoint m_endpoint;

	private:
		static void sort_packets(std::vector<QueuedPacket>& packets);
	};
}

#endif // POLYGUN_NETWORK_NETWORK_MANAGER_HPP
