function initProjectShadowList() {
  $('.download-pdf').on('click', emulateDownloadAction);
}

function emulateDownloadAction(e) {
  e.preventDefault();

  let currentUrl = window.location.href;
  let baseUrl = currentUrl.substring(0, currentUrl.lastIndexOf('/') + 1);
  let pageShoppingListPDF = baseUrl + 'page_my-shopping-list-pdf.html';

  $.ajax({
      type: 'get',
      url: pageShoppingListPDF,
    })
    .done(function (data) {
      const opt = {
        margin: 1,
        filename: 'test',
        image: { type: 'jpeg', quality: 0.98 },
        pagebreak: { avoid: '.order-line-shop-list' },
        html2canvas: { scale: 2, useCORS: true },
        jsPDF: { unit: 'mm', precision: 2 },
      };

      html2pdf().from(data).set(opt).save();
    });
}

function loadScriptWithJQuery(url, attrs) {
  const script = $('<script>');
  script.attr('src', url);

  if (attrs) {
    for (let key in attrs) {
      if (attrs.hasOwnProperty(key)) {
        script.attr(key, attrs[key]);
      }
    }
  }

  $('body').append(script);
}

const html2PdfScriptAttributes = {
  'integrity': 'sha512-1qLXyA3x0VSWeM+8vOotn6+KIRGdcQ8QMzsNeDXmdJsUAnoDGjzlxzqAuUGJGrGkGrtOrq4buDoAHxR89D9PWA==',
  'crossorigin': 'anonymous',
  'referrerpolicy': 'no-referrer',
};

$(document).ready(function () {
  if (!$('.download-pdf').length) {
    return;
  }
  loadScriptWithJQuery('https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.9.3/html2pdf.bundle.min.js', html2PdfScriptAttributes);
  initProjectShadowList();
});
