if (!window.Preview) {
  var Preview = {};
}

/**
 * Namespace for preview manipulation methods
 * @namespace Preview.view
 * @memberof  Preview
 */
Preview.view = (function() {

  /**
   * Run all methods that update the preview
   */
  const parse = () => {
    if (shouldWikiLink) {
      Preview.view.wikiLink();
    }
    if (shouldHighlight) {
      document.querySelectorAll('pre code').forEach((block) => {
        hljs.highlightBlock(block);
      });
    }
    if (shouldRenderMath) {
      renderMathInElement(document.body);
    }
  }

  /**
   * Replace [[wiki links]] in text with url handler search links
   * @alias  wikiLink
   */
  const wikiLink = () => {
    const els = document.querySelectorAll("p,li,dd,dt,td,h1,h2,h3,h4,h5,h6");

    let replacedCode = {},
        codeCounter = 0;

    const codeRemover = (match, p1, offset, string) => {
      codeCounter += 1;
      replacedCode[`nvX-${codeCounter}`] = p1;
      return `||nvX-${codeCounter}||`;
    }

    const codeReplacer = (match, p1, offset, string) => {
      return replacedCode[p1];
    }

    const replacer = (match, p1, p2, offset, string) => {
      let str = p2,
        after = '';

      // if the scroll point marker is inside of our double brackets, remove and
      // re-insert at the end.
      if (/<(a|span) id="MMDHTMLSCROLLPOINT".*?\/\1>/i.test(str)) {
        str = str.replace(/<(a|span) id="MMDHTMLSCROLLPOINT".*?\/\1>/, '');
        after = '<span id="MMDHTMLSCROLLPOINT" style="font-size:0px;position:absolute;left:10px;">.</span>';
      }
      return `<a class="wikilink" href=\'x-nvultra://wiki/?link=${encodeURIComponent(str)}\'>${str}</a>${after}`;
    }



    els.forEach(el => {
      el.innerHTML = el.innerHTML.replace(
        /(<code.*?\/code>)/g,
        codeRemover
      );

      el.innerHTML = el.innerHTML.replace(
        /(\[(?:<(?:a|span) id="MMDHTMLSCROLLPOINT".*?)?\[(.*?)\](?:<(?:a|span) id="MMDHTMLSCROLLPOINT".*?)?\])(?!<\/a)/g,
        replacer
      );

      el.innerHTML = el.innerHTML.replace(
        /\|\|(nvX-\d+)\|\|/g,
        codeReplacer
      );
    });

  }

  return {
    // methods
    parse,
    wikiLink
  };
})();

document.addEventListener("DOMContentLoaded", function(event) {
  Preview.view.parse();
});
