package gabrielbot.core.jda;

import com.github.natanbc.gateway.jdaclient.GatewayClient;
import com.google.common.primitives.Longs;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class GabrielGatewayClient extends GatewayClient {
    private static final Logger LOGGER = LoggerFactory.getLogger(GabrielGatewayClient.class);
    private static final ScheduledExecutorService PING_CALCULATOR = Executors.newSingleThreadScheduledExecutor(r->{
        Thread t = new Thread(r, "Gateway Ping Calculator");
        t.setDaemon(true);
        return t;
    });

    private long ping;

    public GabrielGatewayClient(int shardId, Channel channel) throws IOException {
        super(shardId, channel, true);
        channel.queueDeclare("shard-" + shardId + "-getping", false, false, false, null);
        channel.queueDeclare("shard-" + shardId + "-getping-response", false, false, false, null);
        channel.basicConsume("shard-" + shardId + "-getping-response", true, new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                long now = System.currentTimeMillis();
                ping = now - Longs.fromByteArray(body);
            }
        });
        calculatePing();
        PING_CALCULATOR.scheduleAtFixedRate(this::calculatePing, 30, 30, TimeUnit.SECONDS);
    }

    public long getPing() {
        return ping;
    }

    private void calculatePing() {
        try {
            channel.basicPublish("", "shard-" + shardId + "-getping", null, Longs.toByteArray(System.currentTimeMillis()));
        } catch(IOException e) {
            LOGGER.error("Error calculating gateway ping", e);
        }
    }
}