import { Message, TextChannel } from 'eris';
import { apply as Apply } from '.';
import { Client, Command, RichEmbed } from '../class';

export default class Inquiry_Remove extends Command {
  public applyCommand: Apply;

  constructor(client: Client) {
    super(client);
    this.name = 'rm';
    this.description = 'Removes a Hard Inquiry.';
    this.usage = `${this.client.config.prefix}inquiry rm <inquiry id>`;
    this.aliases = ['remove', 'delete'];
    this.permissions = 4;
    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 inquiry = await this.client.db.Inquiry.findOne({ iid: args[0] });
      if (!inquiry) return this.error(message.channel, 'Unable to find Inquiry.');
      const member = await this.client.util.resolveMember(inquiry.userID, this.mainGuild);
      if (!member) return this.error(message.channel, 'Unable to locate member.');
      const report = await this.client.db.Score.findOne({ userID: member.id });
      if (!report) return this.error(message.channel, 'Unable to locate Community Report.');

      if (inquiry.type !== 0) return this.error(message.channel, 'You can only remove Hard Inquiries.');

      await this.client.db.Inquiry.deleteOne({ iid: args[0] });

      const embed = new RichEmbed();
      embed.setTitle('Inquiry - Removed');
      embed.addField('IID', inquiry.iid);
      embed.addField('Member', `${member.username}#${member.discriminator} | <@${member.id}>`);
      embed.addField('Department/Service', inquiry.name || 'N/A');
      embed.addField('Reason', inquiry.reason || 'N/A');
      embed.setFooter(this.client.user.username, this.client.user.avatarURL);
      embed.setTimestamp();

      const log = <TextChannel> this.client.guilds.get(this.client.config.guildID).channels.get('611584771356622849');
      log.createMessage({ embed });

      const chan = await this.client.getDMChannel(member.id);
      if (chan) {
        chan.createMessage({ embed }).catch(() => {});
      }

      return this.success(message.channel, 'Inquiry successfully deleted.');
    } catch (err) {
      return this.client.util.handleError(err, message, this);
    }
  }
}
