/**
 * jpictures.js
 * JavaScript functions for the pictures galleries.
 */
"use strict";

function convertDate(iso8601_date) {
  const d = new Date(iso8601_date);
  const str = d.toLocaleDateString() + ' ' + d.toLocaleTimeString().replace(/(\d{2}):(\d{2}):(\d{2})/, '$1h$2');
  return str;
}

function createImageGallery(json) {
  var items = [];
  for (let i = 0; i < json.length; i++) {
    const imageUrl   = 'api/picture?id=' + json[i].id;
    const imageTitle = convertDate(json[i].datetime, true) + '<br />' + json[i].title;
    items.push({ src: imageUrl, msrc: imageUrl, w: json[i].width, h: json[i].height, title: imageTitle});
  }

  // Get the PhotoSwipe container
  const pswpElement = document.querySelectorAll('.pswp')[0];

  // Define options
  const options = {
      // core options
      index: 0, // start at first slide
      history: false,
      closeOnScroll: false,
      closeOnVerticalDrag: false
  };

  // Initialize and open PhotoSwipe
  let gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, options);
  gallery.init();
}

function openImagesGallery(selectors) {
  fetch('api/pictures?' + selectors) // selectors is not empty
    .then(response => response.json())
    .then(data => createImageGallery(data));
}