import * as React from 'react';
import {VideoWebView} from './video-webview';

export const isYouTube = (url: string) => {
  return url.indexOf('youtube.com/') > -1;
};

export const getYoutubeEmbed = (url: string) => {
  function getId(url: string) {
    const regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|&v=)([^#&?]*).*/;
    const match = url.match(regExp);

    return match && match[2].length === 11 ? match[2] : null;
  }

  const videoId = getId(url);
  if (videoId) {
    const iframeMarkup = `
      <div style="padding-top: 56.25%; position: relative;">
        <iframe style="position: absolute; top: 0; right: 0; bottom: 0; left: 0;"
          width="100%"
          height="100%"
          src="https://www.youtube.com/embed/${videoId}"
          frameborder="0"
          allow="autoplay; encrypted-media"
          allowfullscreen></iframe>
      <div>
    `;
    return iframeMarkup;
  }
};

export const YouTubeVideo = ({url}: {url: string}) => {
  let iframe = React.useMemo(() => getYoutubeEmbed(url), [url]);
  return <VideoWebView content={iframe || ''} />;
};
