import { Message, Role } from 'eris';
import { createPaginationEmbed } from 'eris-pagination';
import { Client, Command, RichEmbed } from '../class';

export default class Rank extends Command {
  constructor(client: Client) {
    super(client);
    this.name = 'rank';
    this.description = 'Joins/leaves a self-assignable rank. Run this command without arguments to get a list of self-assignable roles.';
    this.usage = `${this.client.config.prefix}rank <rank>`;
    this.permissions = 0;
    this.guildOnly = true;
    this.enabled = true;
  }

  public async run(message: Message, args: string[]) {
    try {
      if (!args[0]) {
        const roles = await this.client.db.Rank.find();
        const rankArray: [{ name: string, value: string }?] = [];
        for (const rank of roles.sort((a, b) => a.name.localeCompare(b.name))) {
          let perms: string;
          if (rank.permissions.includes('0')) {
            perms = 'Everyone';
          } else {
            const rolesArray: Role[] = [];
            rank.permissions.forEach((r) => {
              rolesArray.push(this.mainGuild.roles.get(r));
            });
            perms = rolesArray.map((r) => this.mainGuild.roles.get(r.id)).sort((a, b) => b.position - a.position).map((r) => `<@&${r.id}>`).join(', ');
          }
          let hasRank = false;
          if (message.member.roles.includes(rank.roleID)) hasRank = true;
          rankArray.push({ name: rank.name, value: `${hasRank ? '*You have this role.*\n' : ''}__Description:__ ${rank.description}\n__Permissions:__ ${perms}` });
        }
        const ranksSplit = this.client.util.splitFields(rankArray);
        const cmdPages: RichEmbed[] = [];
        ranksSplit.forEach((split) => {
          const embed = new RichEmbed();
          embed.setTitle('Ranks');
          embed.setDescription(`Use \`${this.client.config.prefix}rank <rank name>\` to join/leave the rank.`);
          embed.setFooter(`Requested by: ${message.author.username}#${message.author.discriminator} | ${this.client.user.username}`, message.author.avatarURL);
          embed.setTimestamp();
          split.forEach((c) => embed.addField(c.name, c.value));
          return cmdPages.push(embed);
        });
        if (cmdPages.length === 1) return message.channel.createMessage({ embed: cmdPages[0] });
        return createPaginationEmbed(message, cmdPages);
      }
      const role = this.client.util.resolveRole(args.join(' '), this.client.guilds.get(this.client.config.guildID));
      if (!role) return this.error(message.channel, 'The role you specified doesn\'t exist.');
      const entry = await this.client.db.Rank.findOne({ roleID: role.id }).lean().exec();
      if (!entry) return this.error(message.channel, 'The rank you specified doesn\'t exist.');
      if (!message.member.roles.includes(entry.roleID)) {
        let permCheck: boolean;
        if (entry.permissions.includes('0')) {
          permCheck = true;
        } else {
          permCheck = entry.permissions.some((item) => message.member.roles.includes(item));
        }
        if (!permCheck) return this.error(message.channel, 'Permission denied.');
        await message.member.addRole(entry.roleID, 'User self-assigned this role.');
        this.success(message.channel, `You have self-assigned ${entry.name}.`);
      } else if (message.member.roles.includes(entry.roleID)) {
        await message.member.removeRole(entry.roleID, 'User has removed a self-assignable role.');
        this.success(message.channel, `You have removed ${entry.name}.`);
      }
      return null;
    } catch (err) {
      return this.client.util.handleError(err, message, this);
    }
  }
}
