import { ensureFile } from "$std/fs/ensure_file.ts";
import { SERVER_STATE } from "../state/serverState.ts";
import { filterTruthy } from "./filters.ts";

const playerListRegex= /There are [0-9] of a max of [0-9]+ players online:/

export const getActivePlayers = (): Promise<PlayerData[]> => new Promise(res => {
  const listener = async (e: CustomEvent<string>) => {
    if (playerListRegex.test(e.detail)) {
      const players: PlayerData[] = []
      const [_, playerString] = e.detail.split(playerListRegex);
      for (const playerName of playerString.split(', ')) {
        players.push(await getPlayerData(playerName));
      }
      res(players.filter(filterTruthy));
      globalThis.removeEventListener('stdoutmsg' as any, listener);
    }
  }
  globalThis.addEventListener('stdoutmsg' as any, listener);
  SERVER_STATE.sendStdIn('list');
})

export type PlayerData = {
  username: string;
  id: string;
  avatar: string;
  banReason?: string;
}

export const getPlayerData = async (username: string) => {
  username = username.trim();
  if (!username) return;
  const cacheFile = 'players.cache.json'
  await ensureFile(cacheFile);
  const cache = JSON.parse(await Deno.readTextFile(cacheFile) || '{}');
  if (!cache[username]) {
    const req = await fetch('https://playerdb.co/api/player/minecraft/' + username, {
      headers: {
        "User-Agent": "MCGRIZZ/0.1 emma@cyborggrizzly.com"
      }
    });
    const json = await req.json();
    cache[username] = json.data.player;
    await Deno.writeTextFile(cacheFile, JSON.stringify(cache, null, 2), {create: true});
  }

  return cache[username]
}
