'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

const index = require('./index-56cc404a.js');

const sparkleYoutubeCss = ":host(.loaded) div.youtube-container{opacity:var(--sparkle-youtube-opacity-loaded, 1)}div.youtube-container{opacity:var(--sparkle-youtube-opacity-not-loaded, 0);transition:var(--sparkle-youtube-transition, opacity 0.15s linear)}";

const SparkleYoutube = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.allowFullscreen = true;
    this.instant = false;
    this.loading = false;
    this.loaded = false;
  }
  async componentWillLoad() {
    await this.addPreconnectLink();
  }
  async componentDidLoad() {
    if (this.instant) {
      await this.lazyLoadContent();
    }
  }
  async updateIFrame(width, height) {
    const iframe = this.el.shadowRoot.querySelector('iframe');
    if (iframe) {
      iframe.width = '' + width;
      iframe.height = '' + height;
    }
  }
  lazyLoadContent() {
    return this.createIFrame();
  }
  async onSrcUpdate() {
    await this.createIFrame();
  }
  play() {
    return this.playPauseVideo(true);
  }
  pause() {
    return this.playPauseVideo(false);
  }
  addPreconnectLink() {
    return new Promise((resolve) => {
      if (!this.src || !document) {
        resolve();
        return;
      }
      const links = document.head.querySelectorAll("link[rel='preconnect'][youtube]");
      if (links && links.length > 0) {
        resolve();
        return;
      }
      const link = document.createElement('link');
      link.rel = 'preconnect';
      link.href = 'https://www.youtube.com';
      link.setAttribute('youtube', '');
      document.head.appendChild(link);
      resolve();
    });
  }
  createIFrame() {
    return new Promise(async (resolve) => {
      if (!this.src) {
        resolve();
        return;
      }
      if (this.loading) {
        resolve();
        return;
      }
      const iframe = this.el.shadowRoot.querySelector('iframe');
      if (iframe && !iframe.parentElement) {
        resolve();
        return;
      }
      this.loading = true;
      this.loaded = false;
      if (iframe) {
        iframe.parentElement.removeChild(iframe);
      }
      const element = document.createElement('iframe');
      const allow = document.createAttribute('allow');
      allow.value = 'accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture';
      this.setAttributeNode(element, allow);
      if (this.allowFullscreen) {
        const allowFullScreen = document.createAttribute('allowfullscreen');
        allowFullScreen.value = '';
        this.setAttributeNode(element, allowFullScreen);
      }
      let src = await this.formatSrc();
      if (!this.allowFullscreen) {
        // Not auto fullscreen on iOS: https://developers.google.com/youtube/player_parameters
        const playsinline = document.createAttribute('playsinline');
        playsinline.value = '1';
        this.setAttributeNode(element, playsinline);
        const split = src.split('?');
        src += `${split && split.length > 0 ? '&' : '?'}playsinline=1`;
      }
      element.src = src;
      element.width = '' + this.width;
      element.height = '' + this.height;
      element.frameBorder = '0';
      element.title = this.frameTitle;
      const div = this.el.shadowRoot.querySelector('div');
      if (!div) {
        resolve();
        return;
      }
      div.appendChild(element);
      this.loading = false;
      this.loaded = true;
      resolve();
    });
  }
  setAttributeNode(element, attr) {
    // Stencil prerendering
    if (element.setAttributeNode === 'function') {
      element.setAttributeNode(attr);
    }
  }
  formatSrc() {
    return new Promise(async (resolve) => {
      // Direct URL can't be embedded, like https://www.youtube.com/watch?v=oUOjJIfPIjw or https://youtu.be/e63Cgln6Yag
      const videoId = await this.findVideoId();
      if (videoId) {
        // In such a case return a link which could be embedded
        resolve('https://www.youtube.com/embed/' + videoId + '?enablejsapi=1');
      }
      else {
        // Otherwise we try the provided url
        if (!this.src) {
          resolve(this.src);
          return;
        }
        // But first, if an embed link, like https://www.youtube.com/embed/PnSNT5WpauE, would be passed, a parameter to enable js should be added otherwise play and pause could not be triggered
        // Therefore we add enablejsapi if needed in any case
        const url = new URL(this.src);
        if (!url.searchParams.get('enablejsapi')) {
          url.searchParams.append('enablejsapi', '1');
        }
        resolve(url.href);
      }
    });
  }
  findVideoId() {
    return new Promise((resolve) => {
      const url = new URL(this.src);
      let videoId = url.searchParams.get('v');
      if (!videoId) {
        const host = url.host;
        if (host === 'youtu.be') {
          // For shortened url
          const pathname = url.pathname;
          if (pathname) {
            const split = url.pathname.split('/');
            if (split && split.length >= 2) {
              videoId = url.pathname.split('/')[1];
            }
          }
        }
      }
      resolve(videoId);
    });
  }
  playPauseVideo(play) {
    return new Promise(async (resolve) => {
      const iframe = this.el.shadowRoot.querySelector('iframe');
      if (!iframe) {
        resolve();
        return;
      }
      iframe.contentWindow.postMessage(JSON.stringify({
        event: 'command',
        func: play ? 'playVideo' : 'pauseVideo',
        args: '',
      }), '*');
      resolve();
    });
  }
  render() {
    const hostClass = this.loaded ? 'loaded' : '';
    return (index.h(index.Host, { class: hostClass }, index.h("div", { class: "youtube-container" })));
  }
  get el() { return index.getElement(this); }
  static get watchers() { return {
    "src": ["onSrcUpdate"]
  }; }
};
SparkleYoutube.style = sparkleYoutubeCss;

exports.sparkle_youtube = SparkleYoutube;
