import qs from 'qs';

const youtubeRegex = /(youtube.com|youtu.be)\/[\s\S](\W|\w)+/;

export const isYoutubeLink = (link: string) =>
  link?.length > 0 && youtubeRegex.test(link);

export const getVideoId = (link: string) => {
  const [url, query] = link.split('?');

  const params = qs.parse(query, { ignoreQueryPrefix: true });
  let videoId = params.v;

  if (!videoId) {
    const urlSplitted = url.split('/');
    videoId = urlSplitted[urlSplitted.length - 1];
  }

  return videoId;
};

export const getEmbedLink = (link: string) => {
  if (!isYoutubeLink(link)) return '';

  const videoId = getVideoId(link);
  const YOUTUBE_EMBED_BASE_URL = 'https://www.youtube.com/embed/';

  return `${YOUTUBE_EMBED_BASE_URL}${videoId}`;
};
