import { Message } from 'eris';
import { Client, 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(message: Message, args: string[]) {
    if (!await this.client.db.Member.exists({ userID: message.author.id })) {
      await this.client.db.Member.create({ userID: message.author.id });
    }
    if (!args[0]) return this.error(message.channel, 'No GitLab profile URL was provided.');
    const member = await this.client.db.Member.findOne({ userID: message.author.id });
    if (!args[0]) {
      await member.updateOne({
        additional: {
          ...member.additional,
          gitlab: null,
        },
      });
      return 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(args[0])) return this.error(message.channel, 'Invalid GitLab profile URL.');

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