import {  TextChannel } from 'eris';
import axios from 'axios';
import { apply as Apply } from '.';
import { Client, CmdContext, 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(ctx: CmdContext) {
    if (!ctx.args[0]) return this.client.commands.get('help').run(new CmdContext(ctx.message, [this.name]));

    const inquiry = await this.client.db.mongo.Inquiry.findOne({ iid: ctx.args[0] });
    if (!inquiry) return this.error(ctx.message.channel, 'Unable to find Inquiry.');
    const member = this.client.util.resolveMember(inquiry.userID, this.mainGuild);
    if (!member) return this.error(ctx.message.channel, 'Unable to locate member.');
    const report = await this.client.db.mongo.Score.findOne({ userID: member.id });
    if (!report) return this.error(ctx.message.channel, 'Unable to locate Community Report.');

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

    await this.client.db.mongo.Inquiry.deleteOne({ iid: ctx.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();

    try {
      await axios({
        method: 'DELETE',
        url: `https://eds.libraryofcode.org/dec/${inquiry.iid}?auth=${this.client.config.internalKey}`,
      });
    } catch (e) {
      this.error(ctx.message.channel, `An error occurred while changing EDS data: ${e}\n*(This does not mean that the operation failed.)*`);
    }

    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(ctx.message.channel, 'Inquiry successfully deleted.');
  }
}
