/* eslint-disable no-useless-return */
import { Message, TextChannel, NewsChannel } from 'eris';
import { Client, Event } from '../class';

export default class CommandHandler extends Event {
  public client: Client;

  constructor(client: Client) {
    super(client);
    this.event = 'messageCreate';
  }

  public async run(message: Message) {
    try {
      this.client.db.Stat.updateOne({ name: 'messages' }, { $inc: { value: 1 } }).exec();
      if (message.author.bot) return;
      if (message.content.indexOf(this.client.config.prefix) !== 0) return;
      const noPrefix: string[] = message.content.slice(this.client.config.prefix.length).trim().split(/ +/g);
      const resolved = await this.client.util.resolveCommand(noPrefix);
      if (!resolved) return;
      if (resolved.cmd.guildOnly && !(message.channel instanceof TextChannel || message.channel instanceof NewsChannel)) return;
      if (!resolved.cmd.enabled) { message.channel.createMessage(`***${this.client.util.emojis.ERROR} This command has been disabled***`); return; }
      if (!resolved.cmd.checkPermissions(this.client.util.resolveMember(message.author.id, this.client.guilds.get('446067825673633794')))) return;
      if ((message.channel.type === 0) && !message.channel.guild.members.get(message.author.id)) {
        message.channel.guild.members.add(await message.channel.guild.getRESTMember(message.author.id));
      }
      this.client.util.signale.log(`User '${message.author.username}#${message.author.discriminator}' ran command '${resolved.cmd.name}' in '${message.channel.id}'.`);
      await resolved.cmd.run(message, resolved.args);
      this.client.db.Stat.updateOne({ name: 'commands' }, { $inc: { value: 1 } }).exec();
    } catch (err) {
      this.client.util.handleError(err, message);
    }
  }
}
