import { Message } from 'eris';
import { Client, Command } from '../class';

export default class Setnick extends Command {
  constructor(client: Client) {
    super(client);
    this.name = 'setnick';
    this.description = 'Changes the nickname of a member.';
    this.usage = `${this.client.config.prefix}setnick <member> [new nickname]`;
    this.permissions = 2;
    this.guildOnly = true;
    this.enabled = true;
  }

  public async run(message: Message, args: string[]) {
    try {
      if (!args[0]) return this.client.commands.get('help').run(message, [this.name]);
      const member = this.client.util.resolveMember(args[0], this.mainGuild);
      if (!member) return this.error(message.channel, 'Cannot find user.');
      let nickname = args.slice(1).join(' ');
      if (args.length === 1) nickname = null;
      if (nickname?.length > 32) return this.error(message.channel, 'New nickname may not be more than 32 characters long.');
      await member.edit({ nick: nickname });
      return this.success(message.channel, `Updated the nickname of ${member.user.username}#${member.user.discriminator}.`);
    } catch (err) {
      return this.client.util.handleError(err, message, this, false);
    }
  }
}
