'use strict';

const config = require('config');
const irc = require('irc');
const logger = require('simple-node-logger').createSimpleLogger();
const { argv } = require('yargs');
// const timers = require('timers/promises');

const {
	onMessage,
	getGames,
} = require('./play');

logger.setLevel(argv.level || 'info');

const client = new irc.Client(config.server, config.user.nick, {
	userName: config.user.username,
	realName: config.user.realName,
	password: config.user.password,
	port: config.port,
	secure: true,
});

async function init() {
	const bot = {
		client,
		rooms: config.channels.map((channel) => ({
			id: channel,
			name: channel,
		})),
	};

	const games = await getGames(bot, config.user.nick);

	client.addListener('registered', () => {
		logger.info('Connected!');
		logger.info('Identifying with NickServ');

		client.say('nickserv', `IDENTIFY ${config.user.username} ${config.user.password}`);

		config.channels.forEach((channel) => {
			logger.info(`Joining ${channel}`);

			client.join(channel, () => logger.info(`Joined ${channel}`));

			if (config.greeting) {
				client.say(channel, config.greeting);
			}
		});

		client.addListener('message', (from, to, body) => onMessage({
			from,
			to,
			body,
			type: 'message',
		}, bot, games));

		client.addListener('error', (error) => {
			logger.error(error);
		});
	});
}

module.exports = init;
