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

export default class Roleinfo extends Command {
  constructor(client: Client) {
    super(client);
    this.name = 'roleinfo';
    this.description = 'Get information about a role.';
    this.usage = 'roleinfo [role ID or role name]';
    this.permissions = 0;
    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 role = this.client.util.resolveRole(args.join(' '), this.mainGuild);
      if (!role) return this.error(message.channel, 'Could not find role.');

      const perms = role.permissions;
      const permsArray: string[] = [];
      if (perms.has('administrator')) permsArray.push('Administrator');
      if (perms.has('manageGuild')) permsArray.push('Manage Server');
      if (perms.has('manageChannels')) permsArray.push('Manage Channels');
      if (perms.has('manageRoles')) permsArray.push('Manage Roles');
      if (perms.has('manageMessages')) permsArray.push('Manage Messages');
      if (perms.has('manageNicknames')) permsArray.push('Manage Nicknames');
      if (perms.has('manageEmojis')) permsArray.push('Manage Emojis');
      if (perms.has('banMembers')) permsArray.push('Ban Members');
      if (perms.has('kickMembers')) permsArray.push('Kick Members');

      const embed = new RichEmbed();
      embed.setTitle('Role Information');
      embed.setDescription(`<@&${role.id}> ID: \`${role.id}\``);
      embed.setColor(role.color);
      embed.addField('Name', role.name, true);
      embed.addField('Color', role.color ? this.client.util.decimalToHex(role.color) : 'None', true);
      embed.addField('Members', String(this.client.guilds.get(this.client.config.guildID).members.filter((m) => m.roles.includes(role.id)).length), true);
      embed.addField('Hoisted', role.hoist ? 'Yes' : 'No', true);
      embed.addField('Position', String(role.position), true);
      embed.addField('Creation Date', `${moment(new Date(role.createdAt)).format('dddd, MMMM Do YYYY, h:mm:ss A')} ET`, true);
      embed.addField('Mentionable', role.mentionable ? 'Yes' : 'No', true);
      embed.setFooter(this.client.user.username, this.client.user.avatarURL);
      embed.setTimestamp();

      if (permsArray.length > 0) {
        embed.addField('Permissions', permsArray.join(', '), true);
      }
      return message.channel.createMessage({ embed });
    } catch (err) {
      return this.client.util.handleError(err, message, this);
    }
  }
}
