const crossrefEndpointBase = "https://api.crossref.org/v1/works/";
const crossrefEndpointTransformSegment = "/transform/application/";

const crossrefFormats = {
  bib: {
    title: "BibTeX",
    transform: "x-bibtex",
    extension: "bib",
  },
  ris: {
    title: "RIS",
    transform: "x-research-info-systems",
    extension: "ris",
  },
};

function populateCrossrefCitation(target) {
  let doi = target.getAttribute("data-doi");
  let pubID = target.getAttribute("data-pub-id");
  let formatKey = target.getAttribute("data-format");
  let format = crossrefFormats[formatKey];

  let endpoint = `${crossrefEndpointBase}${doi}${crossrefEndpointTransformSegment}${format.transform}`;

  let ajaxMessage = document.createElement("div");
  ajaxMessage.classList.add("fsrd-citation__ajax-message");
  ajaxMessage.innerText = `Retreiving the ${format.title} citation from CrossRef.org...`;
  target.appendChild(ajaxMessage);

  fetch(endpoint).then((response) => {
    if (response.ok) {
      response.text().then((text) => {
        let encoded = btoa(unescape(encodeURIComponent(text)));

        target.removeChild(ajaxMessage);

        let accordion = target;
        accordion.classList.add("usa-accordion");

        let accordionHeading = document.createElement("h4");
        accordionHeading.classList.add("usa-accordion__heading");

        let accordionHeadingButton = document.createElement("button");
        accordionHeadingButton.setAttribute("type", "button");
        accordionHeadingButton.classList.add("usa-accordion__button");
        accordionHeadingButton.setAttribute("aria-expanded", "false");
        accordionHeadingButton.setAttribute(
          "aria-controls",
          `fsrd-citation__block--${format.extension}`
        );
        accordionHeadingButton.innerText = format.title;
        accordionHeading.appendChild(accordionHeadingButton);

        accordion.appendChild(accordionHeading);

        // Create the block for the body of the accordion.
        let citationBlock = document.createElement("div");
        citationBlock.id = `fsrd-citation__block--${format.extension}`;
        citationBlock.classList.add("fsrd-citation__block");
        citationBlock.hidden = true;

        // Create the citation text box
        let citationText = document.createElement("p");
        citationText.id = `fsrd-citation__text--${format.extension}`;
        citationText.style.whiteSpace = "pre-wrap";
        citationText.classList.add("fsrd-citation__text");
        citationText.innerText = text;

        citationBlock.appendChild(citationText);
        // Create the button bar.
        let buttonBar = document.createElement("div");
        buttonBar.classList.add("fsrd-citation__button-bar");

        // Create the copy button
        let copyButton = document.createElement("a");
        copyButton.classList.add("usa-button");
        copyButton.href = "#";
        copyButton.setAttribute(
          "onclick",
          `navigator.clipboard.writeText(document.getElementById('${citationText.id}').innerText)`
        );
        copyButton.innerText = "Copy";
        buttonBar.appendChild(copyButton);

        // Create the download button.
        let downloadButton = document.createElement("a");
        downloadButton.classList.add("usa-button");
        downloadButton.href = `data:text/plain;base64,${encoded}`;
        downloadButton.setAttribute("download", `${pubID}.${format.extension}`);
        downloadButton.innerText = "Download";
        buttonBar.appendChild(downloadButton);

        citationBlock.appendChild(buttonBar);

        accordion.appendChild(citationBlock);
      });
    } else {
        ajaxMessage.innerText = `There was an error loading the ${format.title} citation from CrossRef.org. Please try again later.`;
        ajaxMessage.classList.add("fsrd-citation__ajax-message--error");
    }
  });
}

Drupal.behaviors.fsCrossRef = {
  attach: function (context, settings) {
    once('fsCrossRef', '.fsrd-citation__container', context).forEach(
      function(element) {
        populateCrossrefCitation(element);
      }
    )
  }
}