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

export default class Notes extends Command {
  constructor(client: Client) {
    super(client);
    this.name = 'notes';
    this.description = 'Pulls up notes for a member, with an optional categorical filter.';
    this.usage = `${this.client.config.prefix}notes <member> [filter: comm | cs | edu]`;
    this.permissions = 1;
    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]);
      let member: Member | User = this.client.util.resolveMember(args[0], this.mainGuild);
      if (!member) {
        try {
          member = await this.client.getRESTUser(args[0]);
        } catch {
          member = undefined;
        }
      }
      if (!member) return this.error(message.channel, 'User specified could not be found.');

      const notes = await this.client.db.Note.find({ userID: member.id });
      if (!notes || notes?.length < 1) return this.error(message.channel, 'No notes exist for this user.');

      const noteArray: [{ name: string, value: string, inline: boolean }?] = [];
      if (args[1] === 'comm' || args[1] === 'cs' || args[1] === 'edu') {
        switch (args[1]) {
          case 'comm':
            for (const note of notes.sort((a, b) => b.date.getTime() - a.date.getTime()).filter((r) => r.category === 'comm')) {
              noteArray.push({
                name: `${note._id}${note.category === '' ? '' : `, ${note.category.toUpperCase()}`} | ${note.date.toLocaleString('en-us')} ET | Staff: ${this.client.users.get(note.staffID) ? `${this.client.users.get(note.staffID).username}#${this.client.users.get(note.staffID).discriminator}` : 'N/A'}`,
                value: note.text,
                inline: true,
              });
            }
            break;
          case 'cs':
            for (const note of notes.sort((a, b) => b.date.getTime() - a.date.getTime()).filter((r) => r.category === 'cs')) {
              noteArray.push({
                name: `${note._id}${note.category === '' ? '' : `, ${note.category.toUpperCase()}`} | ${note.date.toLocaleString('en-us')} ET | Staff: ${this.client.users.get(note.staffID) ? `${this.client.users.get(note.staffID).username}#${this.client.users.get(note.staffID).discriminator}` : 'N/A'}`,
                value: note.text,
                inline: true,
              });
            }
            break;
          case 'edu':
            for (const note of notes.sort((a, b) => b.date.getTime() - a.date.getTime()).filter((r) => r.category === 'edu')) {
              noteArray.push({
                name: `${note._id}${note.category === '' ? '' : `, ${note.category.toUpperCase()}`}} | ${note.date.toLocaleString('en-us')} ET | Staff: Staff: ${this.client.users.get(note.staffID) ? `${this.client.users.get(note.staffID).username}#${this.client.users.get(note.staffID).discriminator}` : 'N/A'}`,
                value: note.text,
                inline: true,
              });
            }
            break;
          default:
            break;
        }
      } else {
        for (const note of notes.sort((a, b) => b.date.getTime() - a.date.getTime())) {
          noteArray.push({
            name: `${note._id}${note.category === '' ? '' : `, ${note.category}`} | ${note.date.toLocaleString('en-us')} ET | Staff: ${this.client.users.get(note.staffID) ? `${this.client.users.get(note.staffID).username}#${this.client.users.get(note.staffID).discriminator}` : 'N/A'}`,
            value: note.text,
            inline: true,
          });
        }
      }
      const noteSplit = this.client.util.splitFields(noteArray);
      const cmdPages: RichEmbed[] = [];
      noteSplit.forEach((split) => {
        const embed = new RichEmbed();
        embed.setColor('#0000FF');
        embed.setAuthor(`${member.username}#${member.discriminator}`, member.avatarURL);
        embed.setFooter(this.client.user.username, this.client.user.avatarURL);
        embed.setTimestamp();
        split.forEach((c) => embed.addField(c.name, c.value, c.inline));
        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);
    }
  }
}
