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

export default class Mute extends Command {
  constructor(client: Client) {
    super(client);
    this.name = 'mute';
    this.description = 'Mutes a member.';
    this.usage = 'mute <member> [time] [reason]';
    this.permissions = 2;
    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 member = this.client.util.resolveMember(args[0], this.mainGuild);
      if (!member) return this.error(message.channel, 'Cannot find user.');

      try {
        const res1 = await this.client.db.local.muted.get<boolean>(`muted-${member.id}`);
        if (res1 || this.mainGuild.members.get(member.id).roles.includes('478373942638149643')) return this.error(message.channel, 'This user is already muted.');
      } catch {} // eslint-disable-line no-empty
      if (member && !this.client.util.moderation.checkPermissions(member, message.member)) return this.error(message.channel, 'Permission Denied.');
      message.delete();

      let momentMilliseconds: number;
      let reason: string;
      if (args.length > 1) {
        const lockLength = 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 ? args.slice(2).join(' ') : args.slice(1).join(' ');
        if (reason.length > 512) return this.error(message.channel, 'Mute reasons cannot be longer than 512 characters.');
      }
      await this.client.util.moderation.mute(member.user, message.member, momentMilliseconds, reason);
      return this.success(message.channel, `${member.user.username}#${member.user.discriminator} has been muted.`);
    } catch (err) {
      return this.client.util.handleError(err, message, this, false);
    }
  }
}
