import * as Axios from 'axios';
import { IYoutubeVideo } from '../interfaces/youtube-video.interface';
/**
 *Resgata o ID do video
 *
 * @param {string} url
 * @returns {string}
 */
function YouTubeGetID(url: string): string {
   let ID: any = '';

   const newUrl = url.replace(/(>|<)/gi, '').split(/(vi\/|v=|\/v\/|youtu\.be\/|\/embed\/)/);
   if (newUrl[2] !== undefined) {
      ID = newUrl[2].split(/[^0-9a-z_-]/i);
      ID = ID[0];
   } else {
      ID = newUrl;
   }
   return ID;
}

/**
 *Resgata e trata os dados do video
 *
 * @param {string} url
 * @param {string} key
 * @returns {Promise<IYoutubeVideo>}
 */
export const YoutubeService = (url: string, key: string): Promise<IYoutubeVideo | false> => {
   const newId = YouTubeGetID(url);
   return Axios.default
      .get(`https://www.googleapis.com/youtube/v3/videos?part=id%2C+snippet&id=${newId}&key=${key}`)
      .then((xhr) => {
         const items = xhr.data.items;

         if (items.length > 0) {
            return {
               thumbnail: items[0].snippet.thumbnails.standard.url,
               description: items[0].snippet.description,
               title: items[0].snippet.title,
            };
         }

         return false;
      });
};
