#!/usr/bin/env node

import { CreateCommand } from "./commands/create-command";
import { CommandManager } from "./misc/command-manager";
import { VoiceChannelManager } from "./misc/voice-channel-manager";


const chalk = require('chalk');
const clear = require('clear');
const figlet = require('figlet');
const path = require('path');
const discord = require('discord.js');
const client = new discord.Client({ partials: ['MESSAGE', 'CHANNEL', 'REACTION'] });
const mainChannelName = 'pen-and-paper-online';
const voiceLobbyChannelName = 'pnp-lobby';

let mainChannel: any;
let voiceLobbyChannel: any;
let commandManager: CommandManager;
let voiceChannelManger: VoiceChannelManager;

client.on('ready', () => {
    console.log(`Logged in as ${client.user.tag}!`);
    client.channels.cache.find((channel: any) => {


        if (channel.name === voiceLobbyChannelName) {
            voiceLobbyChannel = channel;
            voiceChannelManger = new VoiceChannelManager(voiceLobbyChannel);
        }

        if (channel.name === mainChannelName) {
            mainChannel = channel;
            mainChannel.fetch().then((channel: any) => {
                console.log('update');
            });
            commandManager = new CommandManager(mainChannel, voiceChannelManger);
        }
    });
});

client.on('messageReactionAdd', async (reaction: any, user: any) => {
    // When we receive a reaction we check if the reaction is partial or not
    if (reaction.partial) {
        // If the message this reaction belongs to was removed the fetching might result in an API error, which we need to handle
        try {
            await reaction.fetch();
        } catch (error) {
            console.log('Something went wrong when fetching the message: ', error);
            // Return as `reaction.message.author` may be undefined/null
            return;
        }
    }
    if (reaction.message.channel.name === mainChannelName) {
        const members = reaction.message.guild.members.cache.array();
        const member = getMemberByUserId(members, user.id);
        if (!member.voice.channel) {
            member.createDM().then(
                (dmChannel: any) => {
                    dmChannel.send(`Um einer runde bei zu treten musst du in den voice channel ${voiceLobbyChannelName} sein. Entferne bitte noch einmal dein 👍 und füge ihn wieder hinzu nach dem du der Lobby bei getretten bist!`);
                },
                (err: Error) => {
                    console.error(err);
                }
            );
            return;
        }
        voiceChannelManger.moveUserToChannel(
            member,
            1
        );
    }
});

client.on('message', (msg: any) => {

    if (msg.content) {
        let command = commandManager.extractCommandFromMessage(msg.content);
        if (command) {
            let options = commandManager.extractOptionsFromMessage(msg.content);
            console.log(`Start command ${command} with options ${options}`);
            let commandClass = commandManager.getCommandClass(command);
            if (commandClass !== null) {
                if (options !== null) {
                    commandClass.call(msg, options);
                    return;
                }
                commandClass.call(msg);
            } else {
                msg.reply(`Command \`${command}\` not found.`)
            }
        }
    }
});

client.login('NzE1MjY2NDYwOTUxMjQ4OTM2.Xs63wQ.Fu2xkpgKPa2Tmh-SjW290HZKUeU');


clear();
console.log(
    chalk.red(
        figlet.textSync('Papoh Bot', { horizontalLayout: 'full' })
    )
);



function getMemberByUserId(members: any[], userId: string) {
    for (const member of members) {
        if (member.user.id === userId) {
            return member;
        }
    }
}