<script type="module">
async function extractText(pdf) {
  const pdfjs = (await import('{{ urls.static_plugins("datasette_extract", "pdfjs-dist-4-0-379.js") }}')).default;
  pdfjsLib.GlobalWorkerOptions.workerSrc = '{{ urls.static_plugins("datasette_extract", "pdf.worker.mjs") }}';

  const loadingTask = pdfjsLib.getDocument(pdf);
  const pdfDocument = await loadingTask.promise;

  const numPages = pdfDocument.numPages;
  let pageTextPromises = [];

  for (let i = 1; i <= numPages; i++) {
    pageTextPromises.push(
      pdfDocument.getPage(i).then((page) => page.getTextContent())
    );
  }

  const pageTexts = await Promise.all(pageTextPromises);
  return pageTexts
    .map((item) => item.items.map((text) => text.str).join(" "))
    .join("\n\n");
}

const textarea = document.getElementById('id_content');

function dragOverHandler(event) {
    event.preventDefault();
    event.stopPropagation();
    textarea.classList.add('drag-over');
}
function dragLeaveHandler(event) {
    event.preventDefault();
    event.stopPropagation();
    textarea.classList.remove('drag-over');
}
async function dropHandler(event) {
    event.preventDefault();
    event.stopPropagation();
    textarea.classList.remove('drag-over');
    console.log(event.dataTransfer.files);
    const includeFilenames = event.dataTransfer.files.length > 1;

    var promises = Array.from(event.dataTransfer.files).map(file => {
      return new Promise(async (resolve, reject) => {
        let contentToAdd = '';
        if (includeFilenames) {
          contentToAdd += file.name + '\n\n';
        }
        if (file.type == 'application/pdf') {
          const pdfContent = await extractText(new Uint8Array(await file.arrayBuffer()));
          contentToAdd += pdfContent;
          resolve(contentToAdd);
        } else {
          // Try to read the file as text
          const reader = new FileReader();
          reader.onload = (e) => {
            contentToAdd += e.target.result;
            resolve(contentToAdd);
          };
          reader.onerror = (e) => {
            reject(new Error('Failed to read file'));
          };
          reader.readAsText(file);
        }
      });
    });
    Promise.all(promises).then(contents => {
      textarea.value = contents.join('\n\n');
    });
}

textarea.addEventListener('dragover', dragOverHandler);
textarea.addEventListener('dragleave', dragLeaveHandler);
textarea.addEventListener('drop', dropHandler);
</script>
