// Configure your import map in config/importmap.rb. Read more: https://github.com/rails/importmap-rails
// import "@hotwired/turbo-rails"
// import "controllers"

// import Lightbox from "photoswipe";

import PhotoSwipeLightbox from "photoswipe/lightbox";
const lightbox = new PhotoSwipeLightbox({
  gallery: "#gallery",
  children: "a.foobar",
  pswpModule: () => import("photoswipe"),
});
lightbox.init();

// Initialize the upload form.
function upload_form_init() {
  // Disable the submit button if Javascript is supported.
  // Upload will start right after selecting images.
  const fileSubmit = document.getElementById("file-submit");
  if (fileSubmit)
  {
    fileSubmit.style.display = "none";
  }

  // Install event handler to notice when files were selected.
  document.getElementById("file")?.addEventListener("change", upload_form_files_selected);
}

function upload_form_files_selected() {
  var no_files = this.files.length;
  if (no_files > 0) {
    document.getElementById("file-label").innerHTML = `${no_files} files selected - uploading…`;
    document.getElementById("file-select-button").disabled = true;
    document.getElementById("file-form").submit();

    // $("#file-label").html(no_files + " files selected - uploading…"); // change label
    // $("#file-select-button").attr("disabled", "disabled"); // disable select button
    // $("#file-form").trigger("submit"); // start upload
  }
}

// Handle Ctrl-V to paste an image directly
function upload_paste_handler(event, uploadUrl) {
  console.log("paste!");
  var items = (event.clipboardData || event.originalEvent.clipboardData).items;

  // /*Make Sure Only One File is Copied*/
  // if (items.length != 1) {
  //     return;
  // }

  for (var i = 0; i < items.length; i++) {
    var item = items[i];
    console.log(item);
    console.log("item size=" + item.size);
    if (!item.type.startsWith("image/")) {
      console.log("Skipping file with type " + item.type);
      continue;
    }
    console.log(item.type);
    var file = item.getAsFile();
    console.log(file);
    upload_file_with_ajax(file, uploadUrl);
  }
}

function upload_file_with_ajax(file, uploadUrl) {
  if (file == null) {
    console.log("File was null. Strange.");
    display_error("Maybe the image was too large.");
    return;
  }

  var formData = new FormData();
  formData.append("file", file);
  console.log(formData);

  fetch(uploadUrl, {
    method: "POST",
    body: formData,
    headers: {
      "X-CSRF-Token": document.querySelector('meta[name="csrf-token"]').content,
      // 'Content-Type' is omitted to let the browser set it automatically
      // with the proper boundary for FormData
    },
  })
    .then(async (response) => {
      if (!response.ok) {
        const errorData = await response.json();
        console.log(`AJAX file upload returned error: ${response.statusText}`);
        display_error(errorData);
        throw new Error("Upload failed");
      }
      return response.json();
    })
    .then((data) => {
      console.log("AJAX file upload was ok");
      window.location.replace(after_upload_url);
    })
    .catch((error) => {
      if (error.message !== "Upload failed") {
        console.log(`AJAX file upload error: ${error}`);
      }
    });

  // $.ajax(ajax_upload_url, {
  //   type: "POST",
  //   contentType: false,
  //   processData: false,
  //   data: formData,
  //   //dataType: 'json',
  //   error: function (xhr, txt, err) {
  //     console.log("AJAX file upload returned error: " + txt + " / " + err);
  //     response = JSON.parse(xhr.responseText);
  //     display_error(response);
  //   },
  //   success: function (res) {
  //     console.log("AJAX file upload was ok");
  //     // Go back to details page to show the new upload
  //     window.location.replace(after_upload_url);
  //   },
  // });
}

function display_error(msg) {    console.log("foo");

  // $("#messages").html(
  //   '<div class="callout alert alert-callout-subtle radius">Sorry, pasting did not work. ' + msg + "</div>"
  // );
  document.querySelector("#messages").innerHTML = `
    <div class="callout alert alert-callout-subtle radius">
      Sorry, pasting did not work. ${msg}
    </div>
  `;
}

// function init_fancybox()
// {
//   Fancybox.bind("[data-fancybox]", {
//     // Your custom options
//     // prevEffect	: 'none',
//     // nextEffect	: 'none',
//     // helpers	: {
//     //   title	: {
//     //     type: 'outside'
//     //   },
//     //   thumbs	: {
//     //     width	: 50,
//     //     height	: 50
//     //   }
//     // }
//   });
//   console.log("binding done")
// };


document.addEventListener("DOMContentLoaded", () => {
// document.addEventListener("turbo:load", () => {
  console.log("DOM loaded");
  // Handle uploads on specific views/pages. The DIV with ID
  // #data-js-upload-form carries data attributes that tell us where
  // uploads will be sent from Javascript.
  let element = document.getElementById("data-js-upload-form");

  if (element) {
    console.log("upload_form_init");
    // console.log(element.dataset);
    // console.log(element.dataset.uploadUrl);
    upload_form_init(element.dataset.uploadUrl);
    // document.onpaste = upload_paste_handler(element.dataset.uploadUrl);
    document.onpaste = function(event) { upload_paste_handler(event, element.dataset.uploadUrl); }
  }

  // init_fancybox();
});
