/*
 * Kangaroo Punch MultiPlayer Game Server Mark II
 * Copyright (C) 2020-2021  Scott Duensing
 *
 * This program 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, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program 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 this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 */


#include "console.h"

#include "pong.h"


void clientApiPong(ClientThreadT *client, PacketDecodeDataT *data) {
	struct timespec          timer        = { 0 };
	double                   d            = 0;
	uint64_t                 i            = 0;
	uint64_t                 x            = 0;

	(void)data;

	// Time round-trip.
	clock_gettime(CLOCK_MONOTONIC_RAW, &timer);
	d = (timer.tv_sec - client->pingStart.tv_sec) * 1e9;
	d = (d + (timer.tv_nsec - client->pingStart.tv_nsec)) * 1e-9;
	client->pingStats[client->pingHead] = d;
	client->pingHead++;
	if (client->pingHead >= PING_STATS_SIZE) client->pingHead = 0;
	if (d > client->pingHigh) client->pingHigh = d;
	if (d < client->pingLow)  client->pingLow  = d;
	client->pingAverage = 0;
	x = 0;
	for (i=0; i<PING_STATS_SIZE; i++) {
		if (client->pingStats[i] != 0) {
			x++;
			client->pingAverage += client->pingStats[i];
		}
	}
	client->pingAverage /= (double)x;

	consoleMessageQueue("%ld: Ping: %f  Low: %f  Average: %f  High: %f\n", client->threadIndex, d, client->pingLow, client->pingAverage, client->pingHigh);
}
