'use strict';

const Database = require('../storage/database');
const Invite = require('../invite');

module.exports = {
	'.invite': {
		desc: `The bot will /accept an /invite from you.`,
		ignoreLock: true,
		async function(from) {
			const allowed = await Database.isPlayerAllowedAtSite('*', from);
			// Allow if player has permission at any site
			const sites = await Database.getInviteSites();
			const hasAnySite = sites.some(s => {
				const players = s.players ? s.players.split(',') : [];
				return players.includes(from);
			});
			if (!hasAnySite) return;

			await this.whisper('Coming');
			await this.say(`/invite accept`);
		}
	},
	'inv': {
		desc: `Have a bot invite you to a site.\n  Usage: inv <site>`,
		ignoreLock: true,
		async function(from, site) {
			this.__unLockCommand();

			if (!site) return;

			const siteData = await Database.getInviteSiteByName(site);
			if (!siteData) return;

			const allowed = await Database.isPlayerAllowedAtSite(site, from);
			if (!allowed) return;

			try {
				const bot = this.constructor.bots[siteData.bot_name];
				if (!bot) return;

				await Invite.executeInvite(siteData.bot_name, from);
			} catch (error) {
				console.log('inv error:', error);
				this.whisper('Bot is not available right now, try again in 30 seconds.');
			}
		}
	},
};
