import { api, eventSub } from "index";
import { sendMessage } from "lib/commandUtils";
import { buildTimeString } from "lib/dateManager";
import { redis } from "lib/redis";
import { chatterId, commandPrefix } from "main";

const WHISPERCOOLDOWN = 60 * 5; // 5 minutes

eventSub.onUserWhisperMessage(chatterId, async (msg) => {
	if (!msg.messageText.startsWith(commandPrefix)) {
		await whisper(
			msg.senderUserId,
			`Whisper commands start with '${commandPrefix}'. All whisper commands can be found here: https://gitlab.com/qwerinope/qweribot#whisper-commands-1`,
		);
		return;
	}
	const cmd = msg.messageText
		.slice(commandPrefix.length)
		.trim()
		.toLowerCase()
		.split(" ")[0]!;

	switch (cmd) {
		case "help":
		case "h":
			await whisper(
				msg.senderUserId,
				`All whisper commands can be found here: https://gitlab.com/qwerinope/qweribot#whisper-commands-1`,
			);
			break;
		case "ghostwhisper":
		case "ghost":
		case "g": {
			if ((await redis.ttl(`user:${msg.senderUserId}:timeout`)) < 0) {
				await whisper(
					msg.senderUserId,
					"Cannot send ghost whisper while not timed out",
				);
				return;
			}
			const cooldown = await redis.expiretime(
				`user:${msg.senderUserId}:whispercooldown`,
			);
			if (cooldown < 0) {
				if (msg.messageText.length > 200) {
					await whisper(
						msg.senderUserId,
						`Message too long. Please send a shorter one.`,
					);
					return;
				}
				await redis.set(`user:${msg.senderUserId}:whispercooldown`, "1");
				await redis.expire(
					`user:${msg.senderUserId}:whispercooldown`,
					WHISPERCOOLDOWN,
				);
				await sendMessage(
					`The ghost of ${msg.senderUserDisplayName} whispered: ${msg.messageText
						.split(" ")
						.slice(1)
						.join(" ")
						.replaceAll(/cheer[0-9]+/gi, "")}`,
				);
				await whisper(
					msg.senderUserId,
					`Message sent. You can send another ghost whisper in ${Math.floor(WHISPERCOOLDOWN / 60)} minutes.`,
				);
			} else {
				await whisper(
					msg.senderUserId,
					`Wait another ${buildTimeString(cooldown * 1000, Date.now())} before sending another ghost whisper.`,
				);
			}
			break;
		}
	}
});

const whisper = async (target: string, message: string) =>
	await api.whispers.sendWhisper(chatterId, target, message);
