/**
 *
 * https://www.markdownguide.org/tools/slack/
 *
 */
import emoji from 'node-emoji';

const replaceRegex = function (regex, replacement) {
  return function (str) {
    return str.replace(regex, replacement);
  };
};
const boldReplacer = function (fullMatch, start, content) {
  return `**${content}**`;
};
const strikeThroughReplacer = function (fullMatch, start, content) {
  return `~~${content}~~`;
};
const linkReplacer = function (fullMatch, start, content) {
  const label = start.match(/\|(.*)/)[1]
  const link = start.match(/^(.*?)\|/)[1]

  return !label && !link && content
    ? `[${start}](${start})`
    : `[${label}](${link})`;
};

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 Mrkdwn -> Markdown
 * @param {String} str
 */
export function parseSlackMrkdwnToMarkdown (str) {
  str = replaceBold(str);
  str = replaceStrikeThrough(str);
  str = replaceLink(str);
  str = emoji.emojify(str);
  str = str.replace(/\n/g, '\n\n');
  return str;
}
