import { Message } from 'eris';
import { CmdContext, 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(ctx: CmdContext) {
    if (!ctx.args[0] || ctx.args.length < 1) return this.client.commands.get('help').run(new CmdContext(ctx.message, [this.name]));
    let user = this.client.util.resolveMember(ctx.args[0], this.mainGuild)?.user;
    if (!user) user = await this.client.getRESTUser(ctx.args[0]);
    if (!user) return this.error(ctx.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: ctx.message.author.id,
    };
    if (ctx.args[ctx.args.length - 1] !== 'edu' && ctx.args[ctx.args.length - 1] !== 'comm' && ctx.args[ctx.args.length - 1] !== 'cs') {
      note.category = '';
      note.text = ctx.args.slice(1).join(' ');
    } else {
      note.category = ctx.args[ctx.args.length - 1];
      note.text = ctx.args.slice(0, ctx.args.length - 1).join(' ');
    }
    const saved = await (new this.client.db.mongo.Note(note).save());
    return this.success(ctx.message.channel, `Successfully created Note # \`${saved._id}\`.`);
  }
}
