export const YOUTUBE = 'youtube';
const VIMEO = 'vimeo';
const REGEX_YOUTUBE_VIDEO_ID = /(?:youtu\.be\/|youtube\.com(?:\/embed\/|\/v\/|\/watch\?v=|\/user\/\S+|\/ytscreeningroom\?v=))([\w]{10,12})\b/;

export const getVideoProvider = (url = '') => {
    if (url.includes('youtube') || url.includes('youtu.be')) {
        return YOUTUBE;
    }

    if (url.includes('vimeo')) {
        return VIMEO;
    }

    return null;
};

export const getYoutubePreviewImage = videoId => {
    if (!videoId) {
        return null;
    }

    return `https://img.youtube.com/vi/${videoId}/hqdefault.jpg`;
};

export const getYoutubeVideoId = url => {
    const matchesArray = url && url.match(REGEX_YOUTUBE_VIDEO_ID);

    return matchesArray && matchesArray.length ? matchesArray[1] : null;
};


export const getVideoPreviewImage = url => {
    const videoProvider = url && getVideoProvider(url);

    if (videoProvider === YOUTUBE) {
        const videoId = getYoutubeVideoId(url);

        return videoId && getYoutubePreviewImage(videoId);
    }

    return null;
};
