/**
 * Why we need this stuff:
 * https://www.markdownguide.org/tools/slack/
 *
 */
import emoji from 'node-emoji';

const replaceRegex = function(regex: any, replacement: any) {
  return function(str: string) {
    return str.replace(regex, replacement);
  };
};
const boldReplacer = function(fullMatch: any , start: any, content: string) {
  return `*${content}*`;
};
const strikeThroughReplacer = function(fullMatch: any, start: any, content: string) {
  return `~${content}~`;
};
const linkReplacer = function(fullMatch: any, start: any, content: string) {
  return `<${content}|${start}>`;
};

const boldRegex = /(\*{1,2})(.*?)\1/g;
const strikeThroughRegex = /(~{1,2})(.*?)\1/g;
const linkRegex = /\[([^[]+)\]\(([^)]+)\)/g;

const replaceBold = replaceRegex(boldRegex, boldReplacer);
const replaceStrikeThrough = replaceRegex(
  strikeThroughRegex,
  strikeThroughReplacer
);
const replaceLink = replaceRegex(linkRegex, linkReplacer);

/**
 * Parser from Markdown -> Mrkdwn
 */
export function parseMarkdownToSlackMrkdwn(str: string) {
  str = replaceBold(str);
  str = replaceStrikeThrough(str);
  str = replaceLink(str);
  str = emoji.unemojify(str);
  str = str.replace(/\n\n/g, '\n');

  return str;
}