/*
 * This file is part of OpenTTD.
 * OpenTTD 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, version 2.
 * OpenTTD 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 OpenTTD. If not, see <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
 */

/** @file network_server.h Server part of the network protocol. */

#ifndef NETWORK_SERVER_H
#define NETWORK_SERVER_H

#include "network_internal.h"
#include "core/tcp_listen.h"

class ServerNetworkGameSocketHandler;
/** Make the code look slightly nicer/simpler. */
typedef ServerNetworkGameSocketHandler NetworkClientSocket;
/** Pool with all client sockets. */
using NetworkClientSocketPool = Pool<NetworkClientSocket, ClientPoolID, 8, PoolType::NetworkClient>;
extern NetworkClientSocketPool _networkclientsocket_pool;

/** Class for handling the server side of the game connection. */
class ServerNetworkGameSocketHandler : public NetworkClientSocketPool::PoolItem<&_networkclientsocket_pool>, public NetworkGameSocketHandler, public TCPListenHandler<ServerNetworkGameSocketHandler, PacketGameType, PacketGameType::ServerFull, PacketGameType::ServerBanned> {
protected:
	std::unique_ptr<class NetworkAuthenticationServerHandler> authentication_handler = nullptr; ///< The handler for the authentication.
	std::string peer_public_key{}; ///< The public key of our client.

	NetworkRecvStatus ReceiveClientJoin(Packet &p) override;
	NetworkRecvStatus ReceiveClientIdentify(Packet &p) override;
	NetworkRecvStatus ReceiveClientGameInfo(Packet &p) override;
	NetworkRecvStatus ReceiveClientAuthenticationResponse(Packet &p) override;
	NetworkRecvStatus ReceiveClientGetMap(Packet &p) override;
	NetworkRecvStatus ReceiveClientMapOk(Packet &p) override;
	NetworkRecvStatus ReceiveClientAck(Packet &p) override;
	NetworkRecvStatus ReceiveClientCommand(Packet &p) override;
	NetworkRecvStatus ReceiveClientChat(Packet &p) override;
	NetworkRecvStatus ReceiveClientSetName(Packet &p) override;
	NetworkRecvStatus ReceiveClientQuit(Packet &p) override;
	NetworkRecvStatus ReceiveClientError(Packet &p) override;
	NetworkRecvStatus ReceiveClientRemoteConsoleCommand(Packet &p) override;
	NetworkRecvStatus ReceiveClientNewGRFsChecked(Packet &p) override;
	NetworkRecvStatus ReceiveClientMove(Packet &p) override;

	NetworkRecvStatus SendGameInfo();
	NetworkRecvStatus SendNewGRFCheck();
	NetworkRecvStatus SendWelcome();
	NetworkRecvStatus SendAuthRequest();
	NetworkRecvStatus SendEnableEncryption();

public:
	/** Status of a client */
	enum class ClientStatus : uint8_t {
		Inactive, ///< The client is not connected nor active.
		AuthGame, ///< The client is authorizing with game (server) password.
		Identify, ///< The client is identifying itself.
		NewGRFsCheck, ///< The client is checking NewGRFs.
		Authorized, ///< The client is authorized.
		MapWait, ///< The client is waiting as someone else is downloading the map.
		Map, ///< The client is downloading the map.
		DoneMap, ///< The client has downloaded the map.
		PreActive, ///< The client is catching up the delayed frames.
		Active, ///< The client is active within in the game.
		End, ///< Must ALWAYS be on the end of this list!! (period).
	};

	uint8_t lag_test = 0; ///< Byte used for lag-testing the client
	uint8_t last_token = 0; ///< The last random token we did send to verify the client is listening
	uint32_t last_token_frame = 0; ///< The last frame we received the right token
	ClientStatus status = ClientStatus::Inactive; ///< Status of this client
	CommandQueue outgoing_queue{}; ///< The command-queue awaiting delivery; conceptually more a bucket to gather commands in, after which the whole bucket is sent to the client.
	size_t receive_limit = 0; ///< Amount of bytes that we can receive at this moment

	std::shared_ptr<struct PacketWriter> savegame = nullptr; ///< Writer used to write the savegame.
	NetworkAddress client_address{}; ///< IP-address of the client (so they can be banned)

	ServerNetworkGameSocketHandler(ClientPoolID index, SOCKET s);
	~ServerNetworkGameSocketHandler() override;

	std::unique_ptr<Packet> ReceivePacket() override;
	NetworkRecvStatus CloseConnection(NetworkRecvStatus status) override;
	std::string GetClientName() const;

	void CheckNextClientToSendMap(NetworkClientSocket *ignore_cs = nullptr);

	NetworkRecvStatus SendWait();
	NetworkRecvStatus SendMap();
	NetworkRecvStatus SendErrorQuit(ClientID client_id, NetworkErrorCode errorno);
	NetworkRecvStatus SendQuit(ClientID client_id);
	NetworkRecvStatus SendShutdown();
	NetworkRecvStatus SendNewGame();
	NetworkRecvStatus SendRConResult(uint16_t colour, std::string_view command);
	NetworkRecvStatus SendMove(ClientID client_id, CompanyID company_id);

	NetworkRecvStatus SendClientInfo(NetworkClientInfo *ci);
	NetworkRecvStatus SendError(NetworkErrorCode error, std::string_view reason = {});
	NetworkRecvStatus SendChat(NetworkAction action, ClientID client_id, bool self_send, std::string_view msg, int64_t data);
	NetworkRecvStatus SendExternalChat(std::string_view source, ExtendedTextColour colour, std::string_view user, std::string_view msg);
	NetworkRecvStatus SendJoin(ClientID client_id);
	NetworkRecvStatus SendFrame();
	NetworkRecvStatus SendSync();
	NetworkRecvStatus SendCommand(const CommandPacket &cp);
	NetworkRecvStatus SendConfigUpdate();

	static void Send();
	static void AcceptConnection(SOCKET s, const NetworkAddress &address);
	static bool AllowConnection();

	/**
	 * Get the name used by the listener.
	 * @return the name to show in debug logs and the like.
	 */
	static std::string_view GetName()
	{
		return "server";
	}

	std::string_view GetClientIP();

	/**
	 * Get the public key of our peer.
	 * @return The public key of our client.
	 */
	std::string_view GetPeerPublicKey() const { return this->peer_public_key; }

	static ServerNetworkGameSocketHandler *GetByClientID(ClientID client_id);
};

void NetworkServer_Tick(bool send_frame);
void ChangeNetworkRestartTime(bool reset);

#endif /* NETWORK_SERVER_H */
