import { RCON } from 'minecraft-server-util';

const client = new RCON()

const config = useRuntimeConfig()

let connected = false;

export const sendRconCommand = async (command) => {
  await connectRcon()

  const message = await client.execute(command);

  closeClient()

  return message;
}

const connectRcon = async () => {
  if (connected) return;

  await client.connect(config.rconHost);
  await client.login(config.rconPassword);

  connected = true;
}

const debounce = (callback, wait) => {
  let timeout = null;
  return (...args) => {
    clearTimeout(timeout);
    timeout = setTimeout(() => {
      callback.apply(null, args);
    }, wait);
  };
}

const closeClient = debounce(() => {
  client.close();
  connected = false;
}, 5000)