'use strict';

const config = require('config');

const style = require('../utils/style');
const getWordKey = require('../utils/get-word-key');
const words = require('../../assets/mash-words.json');

const mashes = new Map();

const defineCommands = ['define', 'dict', 'dictionary'];
const resolveCommands = ['solve', 'resolve', 'lookup'];

function start(length, context, attempt = 0) {
	const mash = mashes.get(context.room.id);
	const lengthWords = words[length];

	if (!lengthWords) {
		context.sendMessage(`No words with ${length} letters available`, context.room.id);

		return;
	}

	if (mash) {
		context.sendMessage(`The mash ${style.bold(mash.anagram)} was not guessed, possible answers: ${mash.answers.map((answer) => style.bold(answer.word)).join(', ')}`, context.room.id);
		context.logger.info(`Mash '${mash.anagram}' discarded`);

		mashes.delete(context.room.id);
	}

	const wordEntries = Object.entries(lengthWords);
	const [key, answers] = wordEntries[Math.floor(Math.random() * wordEntries.length)];

	const anagram = key.split('').sort(() => (Math.random() > 0.5 ? 1 : -1)).join('');

	if (answers.some((answer) => answer.word === anagram)) {
		if (attempt >= 10) {
			context.sendMessage(`Sorry, I did not find a mashable ${length}-letter word`);
			return;
		}

		start(length, context, attempt + 1);

		return;
	}

	mashes.set(context.room.id, { key, anagram, answers });

	const newMash = mashes.get(context.room.id);

	context.sendMessage(`Stomp stomp, here's your mash: ${style.bold(style.pink(newMash.anagram))}`, context.room.id);
	context.logger.info(`Mash started, '${anagram}' with answers ${answers.map((answer) => `'${answer.word}'`).join(', ')}`);
}

function play(rawWord, context, shouted) {
	const mash = mashes.get(context.room.id);
	const word = rawWord.trim().toLowerCase();
	const key = getWordKey(word);
	const answer = mash.answers.find((answerX) => answerX.word === word);

	if (!shouted) {
		if (word.length !== mash.key.length) {
			context.sendMessage(`Your answer needs to be ${mash.key.length} letters, ${config.usernamePrefix}${context.user.username}`, context.room.id);
			return;
		}

		if (key !== mash.key) {
			context.sendMessage(`You are not using the letters in ${style.bold(mash.anagram)}, ${config.usernamePrefix}${context.user.username}`, context.room.id);
			return;
		}

		if (word === mash.anagram) {
			context.sendMessage(`${config.usernamePrefix}${context.user.username}... ${config.platform === 'schat' ? ':expressionless:' : '😑'}`, context.room.id);
			return;
		}
	}

	if (answer) {
		const definition = answer.definitions[0] ? `: ${style.italic(`${answer.definitions[0].slice(0, 100)}${mash.answers[0].definitions[0].length > 100 ? '...' : ''}`)}` : '';

		context.sendMessage(mash.answers.length === 1
			? `${style.bold(style.yellow(word))} is the right answer${definition}, ${style.bold(style.cyan(`${config.usernamePrefix}${context.user.username}`))} now has ${style.bold(`${context.user.points + 1} ${context.user.points === 0 ? 'point' : 'points'}`)}! There were no other options for ${style.bold(mash.anagram)}.`
			: `${style.bold(style.yellow(word))} is the right answer${definition}, ${style.bold(style.cyan(context.user.username))} now has ${style.bold(`${context.user.points + 1} ${context.user.points === 0 ? 'point' : 'points'}`)}! Other options for ${style.bold(mash.anagram)}: ${mash.answers.filter((answerX) => answerX.word !== word).map((answerX) => style.italic(answerX.word)).join(', ')}`, context.room.id); // eslint-disable-line max-len

		context.logger.info(`Mash '${mash.anagram}' guessed by '${context.user.username}' with '${word}'`);
		context.setPoints(context.user, 1);

		mashes.delete(context.room.id);

		setTimeout(() => start(word.length, context), 2000);
	}
}

function resolve(word, context) {
	if (!word) {
		context.sendMessage(`Please specify an anagram you would like to resolve, ${config.usernamePrefix}${context.user.username}`, context.room.id);
		return;
	}

	const anagramKey = getWordKey(word);
	const answers = words[word.length]?.[anagramKey];

	if (mashes.get(context.room.id)?.key === anagramKey) {
		context.sendMessage(`Nice try, ${config.usernamePrefix}${context.user.username}. Starting a new mash will cancel the current one, and reveal the answer.`, context.room.id);

		return;
	}

	if (answers?.length > 1 && answers.some((answer) => answer.word === word)) {
		context.sendMessage(`${style.bold(word)} is a valid word in itself, and has the following anagrams, ${config.usernamePrefix}${context.user.username}: ${answers.filter((answer) => answer.word !== word).map((answer) => style.italic(answer.word)).join(', ')}`, context.room.id);
		return;
	}

	if (answers?.length === 1 && answers[0].word === word) {
		context.sendMessage(`${style.bold(word)} is a valid word in itself, but has no anagrams, ${config.usernamePrefix}${context.user.username}`, context.room.id);
		return;
	}

	if (answers?.length > 0) {
		context.sendMessage(`Anagrams of ${style.bold(word)}, ${config.usernamePrefix}${context.user.username}: ${answers.map((answer) => style.italic(answer.word)).join(', ')}`, context.room.id);
		return;
	}

	context.sendMessage(`No anagrams found for ${style.bold(word)}, ${config.usernamePrefix}${context.user.username}`, context.room.id);
}

function define(word, context) {
	if (!word) {
		context.sendMessage(`Please specify word you would like to define, ${config.usernamePrefix}${context.user.username}`, context.room.id);
		return;
	}

	const anagram = getWordKey(word);
	const answers = words[word.length]?.[anagram];
	const answer = answers?.find((answerX) => answerX.word === word);

	if (answer && answer.definitions?.length > 0) {
		context.sendMessage(`${style.bold(word)} can be defined as follows, ${config.usernamePrefix}${context.user.username}: ${style.italic(answer.definitions[0])}`, context.room.id);
		return;
	}

	context.sendMessage(`No definition available for ${style.bold(word)}, ${config.usernamePrefix}${context.user.username}`, context.room.id);
}

function sanitizeDefinition(definition, answers) {
	return definition.replaceAll(/\w+/g, (word) => {
		if (answers.some((answer) => answer.word.includes(word))) {
			return '*'.repeat(word.length);
		}

		return word;
	});
}

function hint(context) {
	const mash = mashes.get(context.room.id);

	if (!mash) {
		context.sendMessage(`There is no mash going on right now, ${config.usernamePrefix}${context.user.username}. Start one with ${config.prefix}mash {length}`, context.room.id);
		return;
	}

	if (mash.anagram.length <= 3) {
		context.sendMessage(`The mash ${style.bold(mash.anagram)} is too short for a hint, ${config.usernamePrefix}${context.user.username}.`, context.room.id);
		return;
	}

	if (mash.anagram.length === 4) {
		context.sendMessage(`Hints for ${style.bold(style.pink(mash.anagram))}, ${config.usernamePrefix}${context.user.username}: ${mash.answers.map((answer) => `${style.bold(`${answer.word.slice(0, 1)} ${'_ '.repeat(answer.word.length - 1).trim()}`)} (${sanitizeDefinition(answer.definitions[0], mash.answers)})`).join(', ')}`, context.room.id);
		return;
	}

	context.sendMessage(`Hints for ${style.bold(mash.anagram)}, ${config.usernamePrefix}${context.user.username}: ${mash.answers.map((answer) => `${style.bold(`${answer.word.slice(0, 1)} ${'_ '.repeat(answer.word.length - 2)}${answer.word.slice(-1)}`)} (${sanitizeDefinition(answer.definitions[0], mash.answers)})`).join(', ')}`, context.room.id);
}

function onCommand(args, context) {
	const mash = mashes.get(context.room.id);
	const word = args[0];
	const length = Number(word);

	if (resolveCommands.includes(context.command) || resolveCommands.includes(context.subcommand)) {
		resolve(word, context);
		return;
	}

	if (defineCommands.includes(context.command) || defineCommands.includes(context.subcommand)) {
		define(word, context);
		return;
	}

	if (['hint'].includes(context.subcommand)) {
		hint(context);
		return;
	}

	if (!Number.isNaN(length)) {
		start(length, context);
		return;
	}

	if (!word && mash) {
		context.sendMessage(`The current mash is: ${style.bold(style.pink(mash.anagram))}`, context.room.id);
		return;
	}

	if (!word || !mash) {
		context.sendMessage(`Start a mash with ${config.prefix}mash [length]`, context.room.id, { styleCommands: true });
		return;
	}

	play(args[0], context);
}

function onMessage(message, context) {
	const mash = mashes.get(context.room?.id);

	if (mash && message.type === 'message' && context.user?.id !== config.user.id) {
		play(message.body, context, true);
	}
}

module.exports = {
	name: 'Mash',
	commands: ['mash', ...defineCommands, ...resolveCommands],
	onCommand,
	onMessage,
	help: `Resolve the anagram. Get a new mash with ${config.prefix}mash [length], look up definitions with ${config.prefix}define [word], resolve an anagram (that's not currently in play) with ${config.prefix}solve [anagram].`,
};
