import axios, { AxiosResponse } from 'axios';
import { Client, CmdContext, Command, RichEmbed } from '../class';

import PGP_Upload from './pgp_upload';
import PGP_Remove from './pgp_remove';

export enum PublicKeyAlgorithm {
  RSA = 1,
  ElGamal = 16,
  DSA = 17,
  ECDH = 18,
  ECDSA = 19,
}

export interface PGPKey {
  status: true;
  fullName: string;
  name: string;
  comment: string;
  email: string;
  creationTime: string;
  publicKeyAlgorithm: PublicKeyAlgorithm;
  fingerprint: string;
  keyID: string;
  bitLength: string;
}

export default class PGP extends Command {
  constructor(client: Client) {
    super(client);
    this.name = 'pgp';
    this.description = 'Uploads to or removes from your account an PGP public key.';
    this.usage = `${this.client.config.prefix}${this.name}`;
    this.permissions = 0;
    this.guildOnly = true;
    this.enabled = true;
    this.subcmds = [PGP_Upload, PGP_Remove];
  }

  public async run(ctx: CmdContext) {
    const profile = await this.client.db.mongo.Member.findOne({ userID: ctx.args[0] || ctx.message.author.id });
    if (!profile) return this.error(ctx.message.channel, 'Unable to find specified member\'s account.');
    const embed = new RichEmbed()
      .setAuthor(`${ctx.message.author.username}#${ctx.message.author.discriminator}`, ctx.message.author.dynamicAvatarURL())
      .setTitle('PGP Connections')
      .setColor('#ffc63c')
      .setDescription(`There are no PGP keys connected to your account. Use \`${this.client.config.prefix}pgp upload\` to add one.`)
      .setTimestamp();
    if (profile?.pgp) {
      embed.setColor('#2ecc71');
      const pgp: AxiosResponse<PGPKey> = await axios.post('https://certapi.libraryofcode.org/pgp', profile.pgp);
      embed.setDescription(`You currently have PGP key **\`${pgp.data.fingerprint.toUpperCase()}\`** owned by ${pgp.data.name} <${pgp.data.email}>.`);
      const pka = Object.keys(PublicKeyAlgorithm).find((key) => PublicKeyAlgorithm[key] === pgp.data.publicKeyAlgorithm);
      if (pka) embed.addField('Public Key Algorithm', pka, true);
      const { comment } = pgp.data;
      if (comment) embed.addField('Comment', comment, true);
      embed.addField('Created At', new Date(pgp.data.creationTime).toUTCString(), true);
    } else this.client.commands.get('help').run(ctx);
    ctx.uniCreateMessage({ embed });
  }
}
