'use strict';

const { CJbot } = require('../model/minecraft');
const { sleep } = require('../utils');
const InviteWeb = require('./invite-web');

class Invite {
	static createRouter = InviteWeb.createRouter;
	static webUI = InviteWeb.webUI;

	constructor(args) { this.bot = args.bot; }
	async init() {}
	async unload() {}

	static async executeInvite(targetBotName, playerName) {
		const bot = CJbot.bots[targetBotName];
		if (!bot) throw new Error(`Bot "${targetBotName}" not found`);

		let wasOffline = !bot.isReady;

		if (!bot.isReady) {
			try {
				await bot.connect();
			} catch (error) {
				console.log('Invite: error connecting to bot', targetBotName);
				throw error;
			}
		}

		await bot.pluginLoad('Tp');
		await bot.bot.chat(`/invite ${playerName}`);

		const disconnectTimeout = setTimeout(() => {
			bot.pluginUnload('Tp');
			if (wasOffline) bot.quit();
		}, 10000);

		bot.on('message', async (message) => {
			if (message.toString() === `${playerName} teleported to you.`) {
				clearTimeout(disconnectTimeout);
				await bot.pluginUnload('Tp');
				if (wasOffline) bot.quit();
			}
		});
	}
}

module.exports = Invite;
