import { createPaginationEmbed } from 'eris-pagination';
import { Client, CmdContext, Command, RichEmbed } from '../class';

export default class DelRedirect extends Command {
  constructor(client: Client) {
    super(client);
    this.name = 'listredirects';
    this.description = 'Delete a redirect link for \'loc.sh\'';
    this.usage = 'listredirects [key || redirect to]';
    this.aliases = ['getredirect', 'lsredirects', 'listlinks', 'lsr', 'gr'];
    this.permissions = 6;
    this.enabled = true;
  }

  public async run(ctx: CmdContext) {
    if (ctx.args[0]) {
      const redirects = await this.client.db.mongo.Redirect.find({ $or: [{ key: ctx.args[0].toLowerCase() }, { to: ctx.args[0].toLowerCase() }] });
      if (redirects.length <= 0) return this.error(ctx.message.channel, 'Could not find an entry matching that query.');
      const embed = new RichEmbed();
      embed.setTitle('Redirect Information');
      for (const redirect of redirects) {
        embed.addField(`${redirect.key} | visited ${redirect.visitedCount} times`, redirect.to);
      }
      embed.setFooter(this.client.user.username, this.client.user.avatarURL);
      embed.setTimestamp();
      return ctx.message.channel.createMessage({ embed });
    }
    const redirects = await this.client.db.mongo.Redirect.find();
    if (!redirects) return this.error(ctx.message.channel, 'No redirect links found.');
    const redirectArray: [{ name: string, value: string }?] = [];
    for (const redirect of redirects) {
      redirectArray.push({ name: `${redirect.key} | visited ${redirect.visitedCount} times`, value: redirect.to });
    }
    const splitRedirects = this.client.util.splitFields(redirectArray);
    const cmdPages: RichEmbed[] = [];
    splitRedirects.forEach((split) => {
      const embed = new RichEmbed();
      embed.setTitle('Redirect Information');
      embed.setTimestamp();
      embed.setFooter(this.client.user.username, this.client.user.avatarURL);
      split.forEach((c) => embed.addField(c.name, c.value));
      return cmdPages.push(embed);
    });
    if (cmdPages.length === 1) return ctx.message.channel.createMessage({ embed: cmdPages[0] });
    return createPaginationEmbed(ctx.message, cmdPages);
  }
}
