/*!
 * Copyright (c) 2018, 2022 Eclipse Foundation, Inc.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v. 2.0 which is available at
 * http://www.eclipse.org/legal/epl-2.0.
 *
 * Contributors:
 *   Eric Poirier <eric.poirier@eclipse-foundation.org>
 *   Olivier Goulet <olivier.goulet@eclipse-foundation.org>
 *
 * SPDX-License-Identifier: EPL-2.0
 */
const eclipseFdnVideos = (function (window, document) {
  (function (root, factory) {
    if (typeof define === 'function' && define.amd) {
      // AMD. Register as an anonymous module.
      define(['ef'], factory);
    } else {
      // Browser globals
      root.eclipseFdnVideos = factory(root.ef);
    }
  })(typeof self !== 'undefined' ? self : this, function (ef) {
    'use strict';

    // Define object
    var eclipseFdnVideos = {};

    /**
     * Replace some videos
     * @public
     * @param {Object} options Videos attributes
     */
    eclipseFdnVideos.replace = function (options) {
      // Default settings
      const default_options = {
        selector: '.eclipsefdn-video',
        resolution: '16by9',
        cookie: {
          name: 'eclipse_cookieconsent_status',
          value: 'allow',
        },
      };

      // Go through the parameters of Options if its defined and is an object
      if (typeof options !== 'undefined' && typeof options === 'object') {
        for (const optionName in default_options) {
          if (
            optionName === 'cookie' &&
            typeof options['cookie'] !== 'object'
          ) {
            continue;
          }
          if (
            typeof options[optionName] === 'undefined' ||
            typeof options[optionName] !== 'string'
          ) {
            continue;
          }
          if (
            optionName === 'resolution' &&
            (options['resolution'] !== '16by9' ||
              options['resolution'] !== '4by3')
          ) {
            continue;
          }
          default_options[optionName] = options[optionName];
        }
      }

      // Select all the videos containing the selector Class
      this.el = document.querySelectorAll(default_options['selector']);

      var cookie_value = '';
      if (typeof default_options['cookie']['name'] !== 'undefined') {
        // Get the cookie consent value
        var value = '; ' + document.cookie;
        var parts = value.split('; ' + default_options['cookie']['name'] + '=');
        if (parts.length >= 2) {
          cookie_value = parts.pop().split(';').shift();
        }
      }

      this.el.forEach(item => {
        const enableJs = item.dataset.enableJs ? true : false;

        // Making sure the url is formatted as we expect it to be
        var link = item
          .getAttribute('href')
          .replace(
            /http(s|):\/\/(www|)(\.|)(youtube\.com\/watch\?v=|youtu\.be\/)/i,
            '//www.youtube-nocookie.com/watch?v='
          );

        // Use youtube-nocookie over youtube.
        link = link.replace('youtube', 'youtube-nocookie');

        if (enableJs) link = link.concat('?enablejsapi=1');

        if (cookie_value === default_options['cookie']['value']) {
          // Create a div to wrap the viewo
          var video_container = document.createElement('div');
          video_container.className =
            'eclipsefdn-video embed-responsive embed-responsive-' +
            default_options['resolution'];
          video_container.innerHTML =
            '<iframe src="' +
            link.replace(/watch\?v\=/i, 'embed/') +
            '" allowfullscreen="allowfullscreen" mozallowfullscreen="mozallowfullscreen" msallowfullscreen="msallowfullscreen" oallowfullscreen="oallowfullscreen" webkitallowfullscreen="webkitallowfullscreen" ></iframe>';

          // Replace the original element with the embeded video
          item.parentNode.replaceChild(video_container, item);
        } else {
          item.setAttribute(
            'class',
            'eclipsefdn-video eclipsefdn-video-with-js'
          );
          if (item.getElementsByTagName('img').length != 1) {
            var video_id = '';
            if (link.includes('//www.youtube-nocookie.com/watch?v=')) {
              video_id = link.replace('//www.youtube-nocookie.com/watch?v=', '');
            }
            if (link.includes('//www.youtube-nocookie.com/embed/')) {
              video_id = link.replace('//www.youtube-nocookie.com/embed/', '');
              if (!link.includes('/playlist?list=')) {
                // Only need to do the change for single video. No need for playlist
                link = link.replace('/embed/', '/watch?v=')
              }
            }
            if (video_id !== '') {
              fetch('https://www.youtube-nocookie.com/oembed?format=json&url=' + link).then(res => res.json()).then(json => {
                const thumbnailResolution = item.dataset.thumbnailResolution;
                let thumbnailUrl;
                const baseThumbnailUrl = `https://i.ytimg.com/vi/${video_id}`;
                
                // Set the thumbnail url based on the thumbnail resolution
                // requested.
                switch (thumbnailResolution) {
                  case 'max':
                    thumbnailUrl = baseThumbnailUrl + '/maxresdefault.jpg';
                    break;
                  case 'hq':
                    thumbnailUrl = baseThumbnailUrl + '/hqdefault.jpg';
                    break;
                  case 'sd':
                    thumbnailUrl = baseThumbnailUrl + '/sddefault.jpg';
                    break;
                  default:
                    thumbnailUrl = json.thumbnail_url;
                }

                item.innerHTML = '<img class="img-responsive" src="'+ thumbnailUrl +'">';
              }); 
            }
          }
        }
      });
    };

    return eclipseFdnVideos;
  });
})(window, document);

export const renderVideos = () => window.eclipseFdnVideos.replace();

window.addEventListener('load', () => {
  renderVideos();
});

export default eclipseFdnVideos;
