package fr.Skydust.JdrBot.tasks;

import fr.Skydust.JdrBot.JdrBot;
import net.dv8tion.jda.api.events.GatewayPingEvent;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Scanner;
import java.util.TimerTask;

public class HeartbeatTask extends TimerTask {
    private String command = "";
    private static boolean heartbeatUpdated = false;

    public HeartbeatTask(String command) {
        this.command = command;
    }

    @Override
    public void run() {
        if(heartbeatUpdated) {
            long ping = JdrBot.jda.getGatewayPing();

            try {
                String[] commandToRun = {"bash", "-c", command.replaceAll("\\{ping\\}", String.valueOf(ping))};
                Process p = Runtime.getRuntime().exec(commandToRun);
                if(JdrBot.debugMode) {
                    System.out.println("DEBUG: Ran command \""+ Arrays.toString(commandToRun) + "\"");
                    try (InputStream inputStream = p.getInputStream(); Scanner s = new Scanner(inputStream).useDelimiter("\\A")) {
                        System.out.println(s.hasNext() ? s.next() : "");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            } catch (Exception e) {
                System.out.println("Error: "+e.getMessage());
            }

            System.out.println("Sent heartbeat "+ ping);

            heartbeatUpdated = false;
        }
    }

    public static void HeartbeatUpdateEvent(GatewayPingEvent e) {
        heartbeatUpdated = true;
    }
}
