#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#include <stddef.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <time.h>
#include <unistd.h>
#include <math.h>
#include <string>

#include "acceptor.h"
#include "log.h"
#include "serverpool.h"
#include "state.pb.h"
#include "stream.h"
#include "udpinput.h"
#include "util.h"
#include "version.h"

using namespace std;

extern ServerPool *servers;

namespace {

// Similar to parse_hostport(), but only parses the IP address,
// and does not use mapped-v4 addresses, since multicast seems
// to not like that too much.
bool parse_ip_address(const string &ip, sockaddr_storage *addr)
{
	memset(addr, 0, sizeof(*addr));

	assert(!ip.empty());
	if (ip[0] == '[') {
		sockaddr_in6 *addr6 = (sockaddr_in6 *)addr;
		addr6->sin6_family = AF_INET6;
		if (ip[ip.size() - 1] != ']') {
			log(ERROR, "address '%s' is malformed; must be either [ipv6addr] or ipv4addr",
				ip.c_str());
			return false;
		}
		string raw_ip(ip.begin() + 1, ip.end() - 1);
		if (inet_pton(AF_INET6, raw_ip.c_str(), &addr6->sin6_addr) != 1) {
			log(ERROR, "'%s' is not a valid IPv6 address", raw_ip.c_str());
			return false;
		}
	} else {
		sockaddr_in *addr4 = (sockaddr_in *)addr;
		addr4->sin_family = AF_INET;
		if (inet_pton(AF_INET, ip.c_str(), &addr4->sin_addr) != 1) {
			log(ERROR, "'%s' is not a valid IPv4 address");
			return false;
		}
	}

	return true;
}

bool maybe_join_multicast_group(int sock, const string &group, const string &source)
{
	if (group.empty()) {
		// Not multicast.
		return true;
	}

	// Join the given multicast group (ASM or SSM).
	// TODO: Also support sources apart from multicast groups,
	// e.g. udp://[::1]:1234 for only receiving from localhost.
	if (!source.empty()) {
		// Single-Source Multicast (SSM).
		group_source_req gsr;
		memset(&gsr, 0, sizeof(gsr));
		if (!parse_ip_address(group, &gsr.gsr_group)) {
			return false;
		}
		if (!parse_ip_address(source, &gsr.gsr_source)) {
			return false;
		}
		int level = (gsr.gsr_group.ss_family == AF_INET) ? SOL_IP : SOL_IPV6;
		if (setsockopt(sock, level, MCAST_JOIN_SOURCE_GROUP, &gsr, sizeof(gsr)) == -1) {
			log_perror("setsockopt(MCAST_JOIN_SOURCE_GROUP)");
			return false;
		}
	} else {
		// Any-Source Multicast (ASM).
		group_req gr;
		memset(&gr, 0, sizeof(gr));
		if (!parse_ip_address(group, &gr.gr_group)) {
			return false;
		}
		int level = (gr.gr_group.ss_family == AF_INET) ? SOL_IP : SOL_IPV6;
		if (setsockopt(sock, level, MCAST_JOIN_GROUP, &gr, sizeof(gr)) == -1) {
			log_perror("setsockopt(MCAST_JOIN_GROUP)");
			return false;
		}
	}

	return true;
}

}  // namespace

UDPInput::UDPInput(const string &url)
	: url(url),
	  sock(-1)
{
	// Should be verified by the caller.
	string protocol;
	bool ok = parse_url(url, &protocol, &user, &host, &port, &path);
	assert(ok);

	construct_header();

	stats.url = url;
	stats.connect_time = time(nullptr);
}

UDPInput::UDPInput(const InputProto &serialized)
	: url(serialized.url()),
	  sock(serialized.sock())
{
	// Set back the close-on-exec flag for the socket.
	// (This can't leak into a child, since we haven't been started yet.)
	fcntl(sock, F_SETFD, FD_CLOEXEC);

	// Should be verified by the caller.
	string protocol;
	bool ok = parse_url(url, &protocol, &user, &host, &port, &path);
	assert(ok);

	construct_header();

	stats.url = url;
	stats.bytes_received = serialized.bytes_received();
	stats.data_bytes_received = serialized.data_bytes_received();
	if (serialized.has_connect_time()) {
		stats.connect_time = serialized.connect_time();
	} else {
		stats.connect_time = time(nullptr);
	}
}

InputProto UDPInput::serialize() const
{
	// Unset the close-on-exec flag for the socket.
	// (This can't leak into a child, since there's only one thread left.)
	fcntl(sock, F_SETFD, 0);

	InputProto serialized;
	serialized.set_url(url);
	serialized.set_sock(sock);
	serialized.set_bytes_received(stats.bytes_received);
	serialized.set_data_bytes_received(stats.data_bytes_received);
	serialized.set_connect_time(stats.connect_time);
	serialized.set_is_metacube_encoded(false);
	return serialized;
}

void UDPInput::close_socket()
{
	safe_close(sock);
	sock = -1;
}
	
void UDPInput::construct_header()
{
	http_header =
		"HTTP/1.0 200 OK\r\n"
		"Content-type: application/octet-stream\r\n"
		"Cache-control: no-cache\r\n"
		"Server: " SERVER_IDENTIFICATION "\r\n"
	        "Connection: close\r\n";
}
	
void UDPInput::add_destination(int stream_index)
{
	stream_indices.push_back(stream_index);
	servers->set_header(stream_index, http_header, "");
}

void UDPInput::do_work()
{
	while (!should_stop()) {
		if (sock == -1) {
			int port_num = atoi(port.c_str());
			sockaddr_in6 addr = create_any_address(port_num);
			sock = create_server_socket(addr, UDP_SOCKET);
			if (sock == -1) {
				log(WARNING, "[%s] UDP socket creation failed. Waiting 0.2 seconds and trying again...",
				             url.c_str());
				usleep(200000);
				continue;
			}

			// The syntax udp://source@group (abusing the username field
			// to store the sender in SSM) seems to be a VLC invention.
			// We mimic it.
			if (!maybe_join_multicast_group(sock, host, user)) {
				log(WARNING, "[%s] Multicast join failed. Waiting 0.2 seconds and trying again...",
				             url.c_str());
				safe_close(sock);
				sock = -1;
				usleep(200000);
				continue;
			}
		}

		// Wait for a packet, or a wakeup.
		bool activity = wait_for_activity(sock, POLLIN, nullptr);
		if (!activity) {
			// Most likely, should_stop was set.
			continue;
		}

		int ret;
		do {
			ret = recv(sock, packet_buf, sizeof(packet_buf), 0);
		} while (ret == -1 && errno == EINTR);

		if (ret < 0) {  // Note that zero-byte packets are legal.
			log_perror("recv");
			close_socket();
			continue;
		}

		{
			lock_guard<mutex> lock(stats_mutex);
			stats.bytes_received += ret;
			stats.data_bytes_received += ret;
		}
	
		for (size_t stream_index : stream_indices) {	
			servers->add_data(stream_index, packet_buf, ret, /*metacube_flags=*/0, /*pts=*/RationalPTS());
		}
	}
}

InputStats UDPInput::get_stats() const
{
	lock_guard<mutex> lock(stats_mutex);
	return stats;
}
