#include <chrono>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <endian.hpp>
#include <network.hpp>

using namespace std::chrono_literals;

int main(){
	uint16_t db_port = 32555;
	auto soc = socket(AF_INET, SOCK_DGRAM, 0);
	struct sockaddr_in addr;
	addr.sin_family = AF_INET;
	addr.sin_port = htons(db_port);
	memset((void*)&addr.sin_addr, 0, sizeof(addr.sin_addr));
	bind(soc,(struct sockaddr*)&addr,sizeof(addr));

	req_rep buffer;
	sockaddr_in client;
	socklen_t packet_sz;

	while(true)
	{
		recvfrom(
			soc, 
			(void*)&buffer, 
			sizeof(req_rep), 
			MSG_WAITFORONE, 
			(struct sockaddr*)&client,
			&packet_sz
		);
		buffer.server_ts = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now().time_since_epoch()).count();

		sendto(
			soc,
			(void*)&buffer, 
			sizeof(req_rep), 
			0,
			(struct sockaddr*)&client,
			(socklen_t)sizeof(client)
		);
	}
}
