/*

Copyright (c) 2015-2018, 2020-2021, Arvid Norberg
All rights reserved.

You may use, distribute and modify this code under the terms of the BSD license,
see LICENSE file.
*/

#include "test.hpp"
#include "test_utils.hpp"
#include "settings.hpp"
#include "setup_swarm.hpp"
#include "utils.hpp"

#include "libtorrent/session.hpp"
#include "libtorrent/alert_types.hpp"
#include "libtorrent/torrent_info.hpp"
#include "libtorrent/add_torrent_params.hpp"
#include "libtorrent/magnet_uri.hpp"
#include "libtorrent/extensions/ut_metadata.hpp"

using namespace lt;

#ifndef TORRENT_DISABLE_EXTENSIONS

using test_flags_t = lt::flags::bitfield_flag<std::uint32_t, struct test_flags_tag>;

namespace test_flags {

	// disconnect immediately after receiving the metadata (to test that
	// edge case, it caused a crash once)
	constexpr test_flags_t disconnect = 0_bit;

	// force encryption (to make sure the plugin uses the peer_connection
	// API in a compatible way)
	constexpr test_flags_t full_encryption = 1_bit;

	// have the downloader connect to the seeder
	// (instead of the other way around)
	constexpr test_flags_t reverse = 2_bit;

	// only use uTP
	constexpr test_flags_t utp = 3_bit;

	// upload-only mode
	constexpr test_flags_t upload_only = 4_bit;

	// re-add the torrent after removing
	constexpr test_flags_t readd = 5_bit;

	// token limit is too low
	constexpr test_flags_t token_limit = 6_bit;

	// add the torrent from a magnet link that only carries the v1
	// info-hash, even though the actual torrent is hybrid. Once the
	// metadata is received the torrent must grow into a hybrid torrent
	constexpr test_flags_t v1_magnet = 7_bit;

	// same as v1_magnet, but the magnet link only carries the v2 info-hash
	constexpr test_flags_t v2_magnet = 8_bit;

} // namespace test_flags

void run_metadata_test(test_flags_t const flags)
{
	using namespace test_flags;

	int metadata_alerts = 0;
	int metadata_failed_alerts = 0;

	sim::default_config cfg;
	sim::simulation sim{cfg};

	lt::settings_pack default_settings = settings();

	if (flags & full_encryption)
		enable_enc(default_settings);

	if (flags & utp)
		utp_only(default_settings);

	if (flags & token_limit)
		default_settings.set_int(settings_pack::metadata_token_limit, 10);


	lt::add_torrent_params default_add_torrent;
	if (flags & upload_only)
	{
		default_add_torrent.flags |= torrent_flags::upload_mode;
	}

#if TORRENT_ABI_VERSION < 4
	std::shared_ptr<lt::torrent_info> ti;
#else
	std::shared_ptr<lt::torrent_info const> ti;
#endif

	// TODO: we use real_disk here because the test disk io doesn't support
	// multiple torrents, and readd will add back the same torrent before the
	// first one is done being removed
	setup_swarm(
		2,
		((flags & reverse) ? swarm_test::upload : swarm_test::download)
			| ((flags & readd) ? swarm_test::real_disk : swarm_test_t{}),
		sim,
		default_settings,
		default_add_torrent,
		// add session
		[](lt::settings_pack&) {},
		// add torrent
		[&ti, flags](lt::add_torrent_params& params) {
			// we want to add the torrent via magnet link
			error_code ec;
			add_torrent_params const p = parse_magnet_uri(
				lt::make_magnet_uri(params), ec);
			TEST_CHECK(!ec);
			ti = params.ti;
			params.ti.reset();
			params.name = p.name;
			params.trackers = p.trackers;
			params.tracker_tiers = p.tracker_tiers;
			params.url_seeds = p.url_seeds;
			params.info_hashes = p.info_hashes;
			// the test torrent is hybrid, so its magnet link normally
			// carries both info-hashes. Drop one of them to add the torrent
			// as if from a single-protocol magnet link and exercise the
			// upgrade-to-hybrid path in torrent::set_metadata()
			if (flags & v1_magnet) params.info_hashes.v2 = sha256_hash{};
			if (flags & v2_magnet) params.info_hashes.v1 = sha1_hash{};
			params.peers = p.peers;
#ifndef TORRENT_DISABLE_DHT
			params.dht_nodes = p.dht_nodes;
#endif
			params.flags &= ~torrent_flags::upload_mode;
		},
		// on alert
		[&](lt::alert const* a, lt::session& ses) {
			if (alert_cast<metadata_failed_alert>(a))
			{
				metadata_failed_alerts += 1;
			}
			else if (auto const* mr = alert_cast<metadata_received_alert>(a))
			{
				metadata_alerts += 1;

				if (flags & (v1_magnet | v2_magnet))
				{
					// even though we added the torrent via a single-protocol
					// magnet link, the metadata describes a hybrid torrent, so
					// the torrent must now have both info-hashes
					auto const tf = mr->handle.torrent_file();
					TEST_CHECK(tf);
					if (tf)
					{
						TEST_CHECK(tf->info_hashes().has_v1());
						TEST_CHECK(tf->info_hashes().has_v2());
					}
				}

				if (flags & disconnect)
				{
					ses.remove_torrent(ses.get_torrents()[0]);
				}

				if (flags & readd)
				{
					add_torrent_params p = default_add_torrent;
					p.ti = ti;
					p.save_path = ".";
					ses.add_torrent(p);
				}
			}
		},
		// terminate
		[&](int ticks, lt::session& ses) -> bool {
			// until the metadata arrives the torrent should only carry the
			// single info-hash from the magnet link. it grows into a hybrid
			// torrent only once the metadata is received
			if ((flags & (v1_magnet | v2_magnet)) && metadata_alerts == 0)
			{
				auto const torrents = ses.get_torrents();
				if (!torrents.empty())
				{
					info_hash_t const ih = torrents[0].info_hashes();
					TEST_EQUAL(ih.has_v1(), bool(flags & v1_magnet));
					TEST_EQUAL(ih.has_v2(), bool(flags & v2_magnet));
				}
			}

			if (flags & reverse)
			{
				return true;
			}

			if (ticks > 70)
			{
				TEST_ERROR("timeout");
				return true;
			}
			if ((flags & token_limit) && metadata_failed_alerts > 0)
			{
				return true;
			}
			if ((flags & disconnect) && metadata_alerts > 0)
			{
				return true;
			}
			if ((flags & upload_only) && has_metadata(ses))
			{
				// the other peer is in upload mode and should not have sent any
				// actual payload to us
				TEST_CHECK(!is_seed(ses));
				return true;
			}

			if (is_seed(ses))
			{
				TEST_CHECK(!(flags & upload_only));
				return true;
			}

			return false;
		});

	if (flags & token_limit)
	{
		TEST_EQUAL(metadata_failed_alerts, 1);
	}
	else
	{
		TEST_EQUAL(metadata_alerts, 1);
	}
}

TORRENT_TEST(ut_metadata_encryption_reverse)
{
	run_metadata_test(test_flags::full_encryption | test_flags::reverse);
}

TORRENT_TEST(ut_metadata_encryption_utp)
{
	run_metadata_test(test_flags::full_encryption | test_flags::utp);
}

TORRENT_TEST(ut_metadata_reverse) { run_metadata_test(test_flags::reverse); }

TORRENT_TEST(ut_metadata_upload_only) { run_metadata_test(test_flags::upload_only); }

TORRENT_TEST(ut_metadata_disconnect) { run_metadata_test(test_flags::disconnect); }

TORRENT_TEST(ut_metadata_disconnect_readd)
{
	run_metadata_test(test_flags::disconnect | test_flags::readd);
}

TORRENT_TEST(ut_metadata_upload_only_disconnect_readd)
{
	run_metadata_test(test_flags::upload_only | test_flags::disconnect | test_flags::readd);
}

TORRENT_TEST(ut_metadata_token_limit) { run_metadata_test(test_flags::token_limit); }

TORRENT_TEST(ut_metadata_v1_magnet_to_hybrid) { run_metadata_test(test_flags::v1_magnet); }

TORRENT_TEST(ut_metadata_v2_magnet_to_hybrid) { run_metadata_test(test_flags::v2_magnet); }

#else
TORRENT_TEST(disabled) {}
#endif // TORRENT_DISABLE_EXTENSIONS
