'use strict';

const config = require('config');
const crypto = require('crypto');
const timers = require('timers/promises');

const style = require('../utils/style');

const wins = {
	rock: 'scissors',
	paper: 'rock',
	scissors: 'paper',
};

const emojis = {
	rock: '🪨',
	paper: '📄',
	scissors: '✂️',
	scissoring: ':scissoring:',
};

const emojiAliases = {
	rock: 'rock',
	paper: 'paper',
	page_facing_up: 'paper',
	page_with_curl: 'paper',
	newspaper: 'paper',
	newspaper_roll: 'paper',
	scroll: 'paper',
	scissors: 'scissors',
	scissoring: 'scissors',
};

const emojiLookup = Object.fromEntries(Object.entries(emojis).map(([key, emoji]) => [emoji, key]));

async function play(context, hand, originalHand) {
	const counter = Object.keys(wins)[crypto.randomInt(0, 3)];

	const userWins = wins[hand] === counter;
	const botWins = wins[counter] === hand;

	await timers.setTimeout(500);
	context.sendMessage(`${emojis.rock} Rock!`, context.room.id);
	await timers.setTimeout(500);
	context.sendMessage(`${emojis.paper} Paper!`, context.room.id);
	await timers.setTimeout(500);

	if (originalHand === 'scissoring') {
		context.sendMessage(`${emojis.scissoring} Scissoring!`, context.room.id);
	} else {
		context.sendMessage(`${emojis.scissors} Scissors!`, context.room.id);
	}

	await timers.setTimeout(750);

	if (userWins) {
		context.sendMessage(`${style.bold('You win!')} ${config.user.username} played ${style.italic(counter)} ${emojis[counter]} against your ${style.italic(originalHand)} ${emojis[originalHand]}`, context.room.id);

		context.setPoints(context.user, 1);
		context.setPoints(config.user, 1);

		return;
	}

	if (botWins) {
		context.sendMessage(`${style.bold('You lose...')} ${config.user.username} played ${style.italic(counter)} ${emojis[counter]} against your ${style.italic(originalHand)} ${emojis[originalHand]}`, context.room.id);

		context.setPoints(context.user, -1);
		context.setPoints(config.user, 1);

		return;
	}

	context.sendMessage(`${style.bold('It\'s a draw.')} ${config.user.username} also played ${style.italic(originalHand)} ${emojis[originalHand]}`, context.room.id);
}

async function onCommand(args, context) {
	return play(context, context.command, context.command);
}

async function onMessage(args, context) {
	const emojiHand = emojiLookup[context.message.body.trim()];
	const emojiAliasHand = config.platform === 'schat' && context.message.originalBody?.trim().match(/^:((?:rock)|(?:paper)|(?:scissors)|(?:scissoring)|(?:page_facing_up)|(?:page_with_curl)):$/)?.[1];

	const hand = emojiHand || emojiAliases[emojiAliasHand];

	if (hand && context.user?.username !== config.user.username) {
		play(context, hand, emojiHand || emojiAliasHand);
	}
}

module.exports = {
	onCommand,
	onMessage,
	name: 'Rock, Paper, Scissors',
	commands: ['rock', 'paper', 'scissors'],
	help: 'Can you read my mind? Play ~rock, ~paper, or ~scissors.',
};
