import { Client, CmdContext, 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(ctx: CmdContext) {
    if (!ctx.args[0]) return this.client.commands.get('help').run(new CmdContext(ctx.message, [this.name]));
    if (!ctx.args[1]) return this.error(ctx.message.channel, 'Permissions are required.');
    if (!ctx.args[2]) return this.error(ctx.message.channel, 'A description is required');
    const role = this.client.util.resolveRole(ctx.args[0], this.mainGuild);
    if (!role) return this.error(ctx.message.channel, 'The role you specified doesn\'t appear to exist.');

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

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

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