// SPDX-FileCopyrightText: 2012 Icinga GmbH <https://icinga.com>
// SPDX-License-Identifier: GPL-2.0-or-later

#ifndef HTTPSERVERCONNECTION_H
#define HTTPSERVERCONNECTION_H

#include "remote/apiuser.hpp"
#include "base/string.hpp"
#include "base/tlsstream.hpp"
#include "base/wait-group.hpp"
#include <memory>
#include <boost/asio/deadline_timer.hpp>
#include <boost/asio/io_context.hpp>
#include <boost/asio/io_context_strand.hpp>
#include <boost/asio/spawn.hpp>
#include <chrono>

namespace icinga
{

using namespace std::chrono_literals;

/**
 * An API client connection.
 *
 * @ingroup remote
 */
class HttpServerConnection final : public Object
{
public:
	DECLARE_PTR_TYPEDEFS(HttpServerConnection);

	HttpServerConnection(const WaitGroup::Ptr& waitGroup, const String& identity, bool authenticated,
		const Shared<AsioTlsStream>::Ptr& stream);

	void Start();
	void StartDetectClientSideShutdown();
	bool Disconnected();

	/**
	 * Sets the liveness timeout.
	 *
	 * If we don't receive any data from the client in this time frame, we consider the connection
	 * dead and close it. The default is 10 seconds. This function should only be used for unit tests
	 * to speed them up.
	 *
	 * @param timeout The timeout duration.
	 */
	void SetLivenessTimeout(std::chrono::milliseconds timeout);

private:
	WaitGroup::Ptr m_WaitGroup;
	ApiUser::Ptr m_ApiUser;
	Shared<AsioTlsStream>::Ptr m_Stream;
	std::chrono::steady_clock::time_point m_Seen{std::chrono::steady_clock::now()};
	std::chrono::milliseconds m_LivenessTimeout{10s};
	String m_PeerAddress;
	boost::asio::io_context::strand m_IoStrand;
	bool m_ShuttingDown;
	bool m_ConnectionReusable;
	boost::asio::deadline_timer m_CheckLivenessTimer;

	HttpServerConnection(const WaitGroup::Ptr& waitGroup, const String& identity, bool authenticated,
		const Shared<AsioTlsStream>::Ptr& stream, boost::asio::io_context& io);

	void Disconnect(boost::asio::yield_context yc);

	void ProcessMessages(boost::asio::yield_context yc);
	void CheckLiveness(boost::asio::yield_context yc);
};

}

#endif /* HTTPSERVERCONNECTION_H */
