import moment, { unitOfTime } from 'moment';
import { User } from 'eris';
import { Client, CmdContext, Command } from '../class';

export default class Ban extends Command {
  constructor(client: Client) {
    super(client);
    this.name = 'ban';
    this.description = 'Bans a member from the guild.';
    this.usage = 'ban <member> [time] [reason]';
    this.permissions = 3;
    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]));
    const member = this.client.util.resolveMember(ctx.args[0], this.mainGuild);
    let user: User;
    if (!member) {
      try {
        user = await this.client.getRESTUser(ctx.args[0]);
      } catch {
        return this.error(ctx.message.channel, 'Cannot find user.');
      }
    } else {
      user = member.user;
    }
    try {
      await this.mainGuild.getBan(ctx.args[0]);
      return this.error(ctx.message.channel, 'This user is already banned.');
    } catch {} // eslint-disable-line no-empty
    if (member && !this.client.util.moderation.checkPermissions(member, ctx.message.member)) return this.error(ctx.message.channel, 'Permission Denied.');
    ctx.message.delete();

    let momentMilliseconds: number;
    let reason: string;
    if (ctx.args.length > 1) {
      const lockLength = ctx.args[1].match(/[a-z]+|[^a-z]+/gi);
      const length = Number(lockLength[0]);
      const unit = lockLength[1] as unitOfTime.Base;
      momentMilliseconds = moment.duration(length, unit).asMilliseconds();
      reason = momentMilliseconds ? ctx.args.slice(2).join(' ') : ctx.args.slice(1).join(' ');
      if (reason.length > 512) return this.error(ctx.message.channel, 'Ban reasons cannot be longer than 512 characters.');
    }
    await this.client.util.moderation.ban(user, ctx.message.member, momentMilliseconds, reason);
    return (await this.success(ctx.message.channel, `${user.username}#${user.discriminator} has been banned.`)).delete();
  }
}
