import { Message } from 'eris';
import { createPaginationEmbed } from 'eris-pagination';
import { Client, 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(message: Message, args: string[]) {
    try {
      if (args[0]) {
        const redirects = await this.client.db.Redirect.find({ $or: [{ key: args[0].toLowerCase() }, { to: args[0].toLowerCase() }] });
        if (redirects.length <= 0) return this.error(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 message.channel.createMessage({ embed });
      }
      const redirects = await this.client.db.Redirect.find();
      if (!redirects) return this.error(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 message.channel.createMessage({ embed: cmdPages[0] });
      return createPaginationEmbed(message, cmdPages);
    } catch (err) {
      return this.client.util.handleError(err, message, this);
    }
  }
}
