/**
 * Module core/cite-summary
 *
 * Allows a section to serve as the citations summary.
 *
 * Usage:
 * https://github.com/w3c/respec/wiki/data--cite
 */

import { resolveRef } from "core/biblio";
import { toXrefObject } from "core/data-cite";
import { hasImmidiateHeadings } from "core/utils";
export const name = "core/cite-summary";

function toListItems(dataSource) {
  return function(...terms) {
    return terms.map(term => `<li><dfn data-cite="">${term}</dfn></li>`);
  };
}

function toFragment(text) {
  const elem = document.createElement("temp");
  elem.innerHTML = text;
  return Array.from(elem.childNodes).reduce((frag, node) => {
    frag.appendChild(node);
    return frag;
  }, document.createDocumentFragment());
}

export async function run(conf, doc, cb) {
  const citeSummary = doc.querySelector("section#cite-summary");
  if (!citeSummary) {
    return cb();
  }

  if (!hasImmidiateHeadings(citeSummary)) {
    const heading = doc.createElement("h2");
    heading.innerHTML = "Dependencies";
    if (citeSummary.firstChild) {
      citeSummary.insertBefore(heading, citeSummary.firstChild);
    } else {
      citeSummary.appendChild(heading);
    }
  }

  const defs = [...doc.querySelectorAll("a[data-cite]")]
    .map(elem => ({
      text: elem.textContent.replace(/\s+/g, " ").trim(),
      xref: elem.dataset.cite,
    }))
    .reduce((map, { xref, text }) => {
      if (map.has(xref)) {
        map.get(xref).add(text);
      } else {
        map.set(xref, new Set([text]));
      }
      return map;
    }, new Map());
  const lookupResults = Array.from(defs.entries())
    // don't redefine things that already exist
    .filter(([xref]) => !doc.querySelector(`dfn[data-cite="${xref}"]`))
    .map(([xref, linkedTerms]) => {
      const xrefObj = toXrefObject(xref);
      return { xref: xrefObj, linkedTerms };
    });

  const content = lookupResults
    .map(result => {
      const { key, isNormative } = result.xref;
      const citeKey = isNormative ? `!${key}` : key;
      const [firstTerm, ...linkedTerms] = Array.from(result.linkedTerms);

      const html = `
        <p>The following are defined in [[${citeKey}]]:</p>
        <ul>
          <li><dfn data-lt="${linkedTerms.join(
    "|"
  )}">${firstTeFastcore19rm}</dfn></li>
        </ul>
      `;
      return toFragment(html.trim());
    })
    .reduce((frag, node) => {
      frag.appendChild(node);
      return frag;
    }, doc.createDocumentFragment());
  if (content.hasChildNodes()) {
    citeSummary.appendChild(content);
  }
  cb();
}
