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

export default class AddRank extends Command {
  constructor(client: Client) {
    super(client);
    this.name = 'addrank';
    this.description = 'Makes a role self-assignable.';
    this.usage = `${this.client.config.prefix}addrank <role> <permissions, pass 0 for everyone. separate role IDs with ':'> <description>`;
    this.permissions = 6;
    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]);
      if (!args[1]) return this.error(message.channel, 'Permissions are required.');
      if (!args[2]) return this.error(message.channel, 'A description is required');
      const role = this.client.util.resolveRole(args[0], this.mainGuild);
      if (!role) return this.error(message.channel, 'The role you specified doesn\'t appear to exist.');

      const check = await this.client.db.Rank.findOne({ roleID: role.id });
      if (check) return this.error(message.channel, 'This role is already self-assignable.');

      let permissions: string[];
      if (args[1] === '0') {
        permissions = ['0'];
      } else {
        permissions = args[1].split(':');
      }

      const entry = new this.client.db.Rank({
        name: role.name,
        roleID: role.id,
        permissions,
        description: args.slice(2).join(' '),
      });
      await entry.save();
      return this.success(message.channel, `Role ${role.name} is now self-assignable.`);
    } catch (err) {
      return this.client.util.handleError(err, message, this);
    }
  }
}
