import { Command, sendMessage } from "lib/commandUtils";
import logger from "lib/logger";
import { streamerId } from "main";
import User from "user";

export default new Command({
	name: "racetime",
	aliases: ["racetime", "raceroom"],
	usertype: "chatter",
	execution: async (msg) => {
		try {
			// this might be some of the worst http code ever
			const streamer = await User.initUserId(streamerId);

			const races = await fetch(`https://racetime.gg/smr/data`).then(
				(a) => a.json() as any,
			);
			if (races.current_races.length < 1) {
				await sendMessage(
					`No Super Metroid Randomizer races active`,
					msg.messageId,
				);
				return;
			}

			for (const race of races.current_races) {
				const data = await fetch(`https://racetime.gg${race.data_url}`).then(
					(a) => a.json() as any,
				);
				for (const racer of data.entrants) {
					if (racer.user.twitch_name === streamer?.username) {
						await sendMessage(`https://racetime.gg${data.url}`, msg.messageId);
						return;
					}
				}
			}
			await sendMessage("Streamer is not in a racetime race.", msg.messageId);
		} catch (err) {
			await sendMessage("Failed to get racetime status", msg.messageId);
			logger.err(err as string);
		}
	},
});
