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

export default class Profile_GitLab extends Command {
  constructor(client: Client) {
    super(client);
    this.name = 'gitlab';
    this.description = 'Updates your GitLab information on your profile.';
    this.usage = `${this.client.config.prefix}profile gitlab <GitLab profile URL>`;
    this.permissions = 0;
    this.enabled = true;
  }

  public async run(ctx: CmdContext) {
    if (!await this.client.db.mongo.Member.exists({ userID: ctx.message.author.id })) {
      await this.client.db.mongo.Member.create({ userID: ctx.message.author.id });
    }
    if (!ctx.args[0]) return this.error(ctx.message.channel, 'No GitLab profile URL was provided.');
    const member = await this.client.db.mongo.Member.findOne({ userID: ctx.message.author.id });
    if (!ctx.args[0]) {
      await member.updateOne({
        additional: {
          ...member.additional,
          gitlab: null,
        },
      });
      return ctx.message.addReaction('modSuccess:578750988907970567');
    }
    const urlRegex = new RegExp(
      '^(https?:\\/\\/)?'
      + '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'
      + '((\\d{1,3}\\.){3}\\d{1,3}))'
      + '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'
      + '(\\?[;&a-z\\d%_.~+=-]*)?'
      + '(\\#[-a-z\\d_]*)?$',
      'i',
    );
    if (!urlRegex.test(ctx.args[0])) return this.error(ctx.message.channel, 'Invalid GitLab profile URL.');

    await member.updateOne({
      additional: {
        ...member.additional,
        gitlab: ctx.args[0],
      },
    });
    return ctx.message.addReaction('modSuccess:578750988907970567');
  }
}
