package network.server;

import java.util.Random;

import network.protocol.packets.KeepAlivePacket;

public class KeepAliveHandler {

	private final ServerConnexion serverConnexion;

	private static final int KEEP_ALIVE_COOLDOWN = 5 * 1000;

	private long lastKeepAlive = 0;
	private long lastSend = 0;
	private volatile boolean keepAliveRecieved = false;

	public KeepAliveHandler(ServerConnexion serverConnexion) {
		this.serverConnexion = serverConnexion;
		sendKeepAlive();
	}

	public boolean update() {
		var currentTime = System.currentTimeMillis();
		if (currentTime - lastSend > KEEP_ALIVE_COOLDOWN) {
			if (keepAliveRecieved) {
				sendKeepAlive();
			} else {
				System.out.println("Zombie");
				serverConnexion.close();
				return false;
			}
		}
		return true;
	}

	public void recievedKeepAlive(long keepAliveId) {
		if (lastKeepAlive == keepAliveId)
			this.keepAliveRecieved = true;
	}

	private void sendKeepAlive() {
		Random r = new Random();
		lastKeepAlive = r.nextLong();
		lastSend = System.currentTimeMillis();
		keepAliveRecieved = false;
		this.serverConnexion.sendPacket(new KeepAlivePacket(lastKeepAlive));
	}

}
