import { Message } from 'eris';
import { Command, Client } from '../class';

export default class AddNote extends Command {
  constructor(client: Client) {
    super(client);
    this.name = 'addnote';
    this.description = 'Adds a note to a member.';
    this.usage = `${this.client.config.prefix}addnote <member> <text> [category: comm | cs | edu]`;
    this.permissions = 1;
    this.guildOnly = true;
    this.enabled = true;
  }

  public async run(message: Message, args: string[]) {
    try {
      if (!args[0] || args.length < 1) return this.client.commands.get('help').run(message, [this.name]);
      let user = this.client.util.resolveMember(args[0], this.mainGuild)?.user;
      if (!user) user = await this.client.getRESTUser(args[0]);
      if (!user) return this.error(message.channel, 'The member you specified could not be found.');

      const note: { userID?: string, staffID: string, date: Date, category?: string, text?: string } = {
        userID: user.id,
        date: new Date(),
        staffID: message.author.id,
      };
      if (args[args.length - 1] !== 'edu' && args[args.length - 1] !== 'comm' && args[args.length - 1] !== 'cs') {
        note.category = '';
        note.text = args.slice(1).join(' ');
      } else {
        note.category = args[args.length - 1];
        note.text = args.slice(0, args.length - 1).join(' ');
      }
      const saved = await (new this.client.db.Note(note).save());
      return this.success(message.channel, `Successfully created Note # \`${saved._id}\`.`);
    } catch (err) {
      return this.client.util.handleError(err, message, this);
    }
  }
}
