
// Konfiguration
const fp_youtube_consent_unblock_functions = [];
let fp_youtube_consent_was_accepted = false;
const networks = [{
  name: 'youtube',
  videoFormat: 'video/youtube',
  uri: /(?:https?:\/\/)?(?:www\.)?youtu\.?be(?:\.com)?\/?.*(?:watch|embed)?(?:.*v=|v\/|\/)([\w\-_]+)\&?/i
}, {
  name: 'vimeo',
  videoFormat: 'video/vimeo',
  uri: /(?:https?:\/\/)?(?:player\.)?vimeo(?:\.com)?\/?.*(?:watch|embed)?(?:.*v=|v\/|\/)([\w\-_]+)\&?/i
}];
let fp_youtube_consent_overlay_typenum, fp_youtube_consent_thumbnail_typenum;
if (document.currentScript) {
  fp_youtube_consent_overlay_typenum = document.currentScript?.getAttribute('data-overlay');
  fp_youtube_consent_thumbnail_typenum = document.currentScript?.getAttribute('data-thumbnail');
} else {
  fp_youtube_consent_overlay_typenum = document.querySelector('script[data-overlay][data-thumbnail]')?.getAttribute('data-overlay');
  fp_youtube_consent_thumbnail_typenum = document.querySelector('script[data-overlay][data-thumbnail]')?.getAttribute('data-thumbnail');
}
if (!fp_youtube_consent_overlay_typenum) fp_youtube_consent_overlay_typenum = document.querySelector('meta[name="fp:youtube-consent:overlay"]')?.getAttribute('content');

// Wir sperren erst mal alles!
document.addEventListener("DOMContentLoaded", function () {
  blockAll();
});
// Wenn alles geladen ist fragen wir mal nach, ob Youtube genehmigt!
window.addEventListener("load", function () {
  fp_youtube_consent_is_accepted().then(accepted => {
    if (accepted) unblockAll();
  });
});

/**
 * Blockiert alle Videos auf der Seite.
 */
function blockAll() {
  // Wir prüfen alle Netzwerke (zurzeit nur Youtube hrhr)
  for (const network of networks) {
    // Alle Overlay bearbeiten
    for (const overlay of document.querySelectorAll('.fp_youtube_consent')) {
      processOverlay(overlay);
    }

    // Alle Videos bearbeiten
    // ToDo!

    // Alle iFrames bearbeiten
    for (const iframe of document.getElementsByTagName('iframe')) {
      if (network.uri.test(iframe.src)) {
        processIframe(iframe);
      }
    }
  }
}

/**
 * Bearbeitet ein erkanntes Overlay.
 * @param overlay
 */
function processOverlay(overlay) {
  const consent = overlay.querySelector('.consent-bg');
  const iframe = overlay.querySelector('iframe');
  const button = overlay.querySelector('a.accept');

  // Unblock Funktion hinzufügen
  fp_youtube_consent_unblock_functions.push(() => {
    overlay.classList.remove('fp_youtube_consent');
    iframe.src = iframe.getAttribute("data-src");
    consent?.remove();
  });

  // Button zum Unblocken mit Listener belegen.
  if (button) button.onclick = ev => {
    ev.preventDefault();

    // Consenttools mitteilen, dass akzeptiert
    setConsent(true, button);
    // Video entsperren
    unblockAll();
  };
}

/**
 * Bearbeitet ein erkanntes iFrame.
 * @param iframe
 */
function processIframe(iframe) {
  // Prüfen ob es ein wrapper-Element gibt
  let wrapper = iframe;
  const parentClasses = wrapper.parentElement.classList;
  if (parentClasses.contains('videoWrapper') || parentClasses.contains('ratio') || parentClasses.contains('embed-responsive')) {
    wrapper = wrapper.parentElement;
  }

  // iFrame sourcen leeren
  var iFrameSrc = iframe.src.split("?")[0];
  iframe.setAttribute("data-src", iFrameSrc);
  iframe.src = "";

  // Wrapper um den Wrapper legen
  var overlaywrapper = document.createElement('div');
  overlaywrapper.className = "fp_youtube_consent";
  //overlaywrapper.style.width = iframe.width + "px";
  //overlaywrapper.style.height = iframe.height + "px";
  wrapper.parentElement.appendChild(overlaywrapper);
  overlaywrapper.appendChild(wrapper);

  // Overlay laden über Middleware
  var ajaxUrl = "//" + window.location.hostname + window.location.pathname + "?type=" + fp_youtube_consent_overlay_typenum + "&src=" + decodeURIComponent(iFrameSrc);
  httpGet(ajaxUrl).then(data => {
    var html = htmlToElement(data);
    //html.style.width = iframe.width + "px";
    //html.style.height = iframe.height + "px";
    overlaywrapper.appendChild(html);
    processOverlay(overlaywrapper);
  });
}

/**
 * Blockiert ein direkt eingebundenes Video Element (z.B. Video JS!)
 * @param video
 */
function processVideo(video) {
  // ToDo!
}

/**
 * Teilt den Consent-Tools eine Änderung mit.
 * @param accepted
 * @param button
 * @returns {boolean}
 */
function setConsent(accepted, button) {
  try {
    fp_youtube_consent_set_accept(accepted, button);
  } catch (err) {
    console.log(err);
  }
  return false;
}

/**
 * Entsperrt alle Videos indem es alle gespeicherten Unblock-Funktionen aufruft.
 */
function unblockAll() {
  fp_youtube_consent_unblock_functions.forEach(method => {
    method();
  });
}

/**
 * Blockt oder Entblockt die Videos.
 */
function fp_youtube_consent_accept_e() {
  fp_youtube_consent_is_accepted().then(accepted => {
    if (fp_youtube_consent_was_accepted != accepted) {
      fp_youtube_consent_was_accepted = accepted;
      if (accepted) {
        unblockAll();
      } else {
        blockAll();
      }
    }
  });
}

/**
 * Führt eine AJAX-Abfrage durch.
 * @param theUrl
 * @returns {Promise<unknown>}
 */
function httpGet(theUrl) {
  return new Promise(function (resolve, reject) {
    const xmlHttp = new XMLHttpRequest();
    xmlHttp.open("GET", theUrl, true);
    xmlHttp.send();
    xmlHttp.onreadystatechange = e => {
      if (xmlHttp.readyState == 4 && xmlHttp.status == 200) resolve(xmlHttp.responseText);
    };
  });
}

/**
 * Wandelt einen String in ein HTML-Element um.
 * @param html
 * @returns {ChildNode}
 */
function htmlToElement(html) {
  html = html.trim();
  const temp = document.createElement('div');
  temp.innerHTML = html;
  return temp.firstChild;
}
const youtube_consent_id = "BJz7qNsdj-7";

/**
 * Speichert das akzeptieren des Cookies.
 */
function fp_youtube_consent_set_accept(accepted) {
  if (typeof UC_UI !== "undefined") {
    if (accepted) {
      UC_UI.acceptService(youtube_consent_id);
    } else {
      UC_UI.rejectService(youtube_consent_id);
    }
  }
}

/**
 * Prüft ob der Consent akzeptiert wurde.
 */
function fp_youtube_consent_is_accepted() {
  return new Promise(function (resolve, reject) {
    if (typeof UC_UI !== "undefined") {
      var services = UC_UI.getServicesBaseInfo();
      for (var i = 0; i < services.length; i++) {
        var service = services[i];
        if (service.id === youtube_consent_id) {
          resolve(service.consent.status === true);
        }
      }
    }
    resolve(false);
  });
}

/**
 * Wenn irgendwas geändert wird im Consent Tool reagieren
 */
window.addEventListener("ucEvent", function (e) {
  fp_youtube_consent_is_accepted().then(accepted => {
    if (accepted) unblockAll();
  });
});

/**
 * Sobald UserCentrics initialisiert wurde.
 */
window.addEventListener('UC_UI_INITIALIZED', function (event) {
  fp_youtube_consent_is_accepted().then(accepted => {
    if (accepted) unblockAll();
  });
});

/**
 * Wenn das Cookie durch das Banner akzeptiert wird Videos automatisch entblocken.

$(document).on('click', '#uc-center-container button', function() {
	fp_youtube_consent_is_accepted().then((accepted) => {
		if(accepted) fp_youtube_consent_unblock();
	});
}); */